Split Array into Consecutive Subsequences

Decide whether a sorted array can be split into runs of at least three consecutive numbers.

Given an array of integers nums sorted in non-decreasing order, each number at least as big as the one before it, decide whether it can be split into subsequences that follow two rules. Return true if it can, and false otherwise. A subsequence is made of numbers picked from the array in their original order, not necessarily next to each other. Each subsequence must be consecutive integers, each one more than the one before it, and must hold at least 3 numbers. Every number of the array goes into exactly one subsequence.

Example 1
Input: nums = [1, 2, 3, 3, 4, 5]
Output: true
Explanation: [1, 2, 3] and [3, 4, 5].
Example 2
Input: nums = [1, 2, 3, 3, 4, 4, 5, 5]
Output: true
Explanation: [1, 2, 3, 4, 5] and [3, 4, 5].
Example 3
Input: nums = [1, 2, 3, 4, 4, 5]
Output: false
Solution

The Idea

In some card games you lay down a straight: three or more cards in a row, such as 4, 5 and 6. This problem hands us a sorted pile of numbers and asks whether all of them can be laid down as straights of at least three. We will call each such straight a run.

Take Example 2, [1, 2, 3, 3, 4, 4, 5, 5]. One way that works is the run 1, 2, 3, 4, 5 and the run 3, 4, 5. Look at the picture below. The row labelled run A collects 1, 2, 3, then the first 4 and the first 5. The row labelled run B takes the second 3, the second 4 and the second 5.

The sorted array 1, 2, 3, 3, 4, 4, 5, 5 split into two runs. Run A is 1, 2, 3, 4, 5 and run B is 3, 4, 5. The first 4 arrives while run A waits for 4, so it extends run A.

Read the array from left to right, the way the picture does. Each number has two places it can go: onto the end of a run that is waiting for it, or into a brand new run. When the first 4 arrives, run A already holds 1, 2, 3 and is waiting for a 4, so the highlighted 4 joins run A.

A new run is the costly choice. It must reach three numbers, so it needs the next two numbers as well, and the safe way is to take them at once. In the picture, run B starts at the second 3 and takes a 4 and a 5 right away. Because of that, every run starts with three numbers.

So which choice is right when a number could do both? Joining a waiting run is never worse. The waiting run already has three numbers, so it is complete either way, and adding the number uses up nothing else. A new run would take the next two numbers, and a later run might need exactly those.

Take [1, 2, 3, 4, 5, 5, 6, 7]. The 4 should join 1, 2, 3. A new run 4, 5, 6 would take the only 6, and the second 5 needs that 6 for 5, 6, 7.

So the key insight is: extend a waiting run if there is one, and otherwise start a new run and take its next two numbers right away. If neither works, the number has nowhere to go and the answer is false.

Solution Approach

Turning that idea into code means settling four things: why not simply try every split, in which order the two choices are tried, how to remember the runs, and what to do with numbers a new run has already taken.

Trying every split

Why not try every way to share the numbers among runs? Each number may go into any of the runs open at that moment, and every choice multiplies the cases, so the count grows exponentially. Placing each number once, by a fixed rule, and never moving it later avoids all that. A method that commits to the best-looking choice at each step like this is called greedy.

Extending before starting

In which order are the two choices tried? Call the number being read x. Extending comes first, because it uses up no other numbers, as the 4 in [1, 2, 3, 4, 5, 5, 6, 7] showed. A new run is started only when no run waits for x, and it takes x + 1 and x + 2 on the spot.

Why take the next two numbers now instead of waiting for them? Taking them at once means no run is ever left open with only one or two numbers, so when the reading ends, every run is long enough. And if x + 1 or x + 2 has no free copy now, none will turn up later, because copies only get used up as the reading moves right.

Remembering the runs

Do we need to keep each run's numbers? No. All that matters about a run is which number it waits for next. A HashMap named waitingFor maps a value to how many runs wait for it. Extending with x moves one run from waiting for x to waiting for x + 1.

A second HashMap, unplaced, counts the copies of each value not yet in any run. Maps keyed by the value itself also work for negative numbers, which an array indexed by value could not hold.

Copies a new run already took

What happens when the reading reaches a number that a new run took earlier? In Example 2, starting run B at the second 3 takes a 4 and a 5 ahead of time. When the reading later reaches the second 4, unplaced shows no 4 left, because the first 4 went to run A and the other to run B, so that 4 is skipped.

Java Solution

The method isPossible works in these steps:

  1. First, count the copies of every value in a HashMap named unplaced, with one loop over nums and unplaced.merge(x, 1, Integer::sum).
  2. Create the second map, waitingFor, empty, since no run exists yet.
  3. Loop over nums again, taking each number x in order. If unplaced holds no copy of x, a new run took it earlier, so skip it. Otherwise take one copy.
  4. If some run waits for x, extend it: one fewer run waits for x and one more waits for x + 1.
  5. Otherwise, if x + 1 and x + 2 both have a free copy, start a new run: take one copy of each, and record a run that waits for x + 3.
  6. If neither works, return false at once. When the loop places every number, return true.

The main method runs the three examples, the array from The Idea where starting a new run too early goes wrong, an array of only two numbers, and an array with negative numbers.

Java
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class SplitArrayIntoConsecutiveSubsequences {

    public static boolean isPossible(int[] nums) {
        Map<Integer, Integer> unplaced = new HashMap<>();  // copies of each value not yet placed
        for (int x : nums) {
            unplaced.merge(x, 1, Integer::sum);
        }
        Map<Integer, Integer> waitingFor = new HashMap<>(); // runs whose next value is the key

        for (int x : nums) {
            if (unplaced.get(x) == 0) {
                continue;                          // this copy was taken by a new run earlier
            }
            unplaced.merge(x, -1, Integer::sum);

            if (waitingFor.getOrDefault(x, 0) > 0) {
                waitingFor.merge(x, -1, Integer::sum);     // extend a run that ends at x - 1
                waitingFor.merge(x + 1, 1, Integer::sum);  // that run now waits for x + 1
            } else if (unplaced.getOrDefault(x + 1, 0) > 0
                    && unplaced.getOrDefault(x + 2, 0) > 0) {
                unplaced.merge(x + 1, -1, Integer::sum);   // start x, x + 1, x + 2
                unplaced.merge(x + 2, -1, Integer::sum);
                waitingFor.merge(x + 3, 1, Integer::sum);  // the new run waits for x + 3
            } else {
                return false;                      // x fits nowhere
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int[][] inputs = {
            {1, 2, 3, 3, 4, 5},
            {1, 2, 3, 3, 4, 4, 5, 5},
            {1, 2, 3, 4, 4, 5},
            {1, 2, 3, 4, 5, 5, 6, 7},
            {1, 2},
            {-1, 0, 1, 1, 2, 3}
        };
        for (int[] nums : inputs) {
            System.out.println(Arrays.toString(nums) + " -> " + isPossible(nums));
        }
    }
}

Running it prints:

Output
[1, 2, 3, 3, 4, 5] -> true
[1, 2, 3, 3, 4, 4, 5, 5] -> true
[1, 2, 3, 4, 4, 5] -> false
[1, 2, 3, 4, 5, 5, 6, 7] -> true
[1, 2] -> false
[-1, 0, 1, 1, 2, 3] -> true

Look at the line for [1, 2, 3, 4, 4, 5], which prints false. The 1 starts the run 1, 2, 3, and the first 4 extends it, so that run now waits for 5. The second 4 finds no run waiting for 4, and it cannot start 4, 5, 6 because the array has no 6.

The line for [1, 2, 3, 4, 5, 5, 6, 7] prints true, from the runs 1, 2, 3, 4, 5 and 5, 6, 7. The order of the two choices matters here. With the extend and start branches swapped, the same input returns false: the 4 starts 4, 5, 6, and the second 5 then finds no free 6 and no run waiting for 5.

[1, 2] prints false because the 1 needs a 3 to start a run. The last line, true, comes from the runs -1, 0, 1 and 1, 2, 3, so negative values work as map keys like any other.

Complexity

The work is two passes over the array, with a few map operations for each number.

  • Time: O(n), because each of the n numbers is counted once in the first loop and placed or skipped once in the second, using a fixed number of HashMap operations that take constant time on average.
  • Space: O(n), because unplaced has one entry per distinct value and each number adds at most one new key to waitingFor.

Another greedy method that places items one at a time and stops as soon as one has nowhere to go is Reorganize String.