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 numstruefalse
Example 1
Output: true
Explanation: [1, 2, 3] and [3, 4, 5].
Example 2
Output: true
Explanation: [1, 2, 3, 4, 5] and [3, 4, 5].
Example 3
Output: false
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]
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]
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 xxx + 1x + 2
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 + 1x + 2
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 HashMapwaitingForxxx + 1
A second HashMapunplaced
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
Java Solution
The method isPossible
- First, count the copies of every value in a
namedHashMap , with one loop overunplaced andnums .unplaced.merge(x, 1, Integer::sum) - Create the second map,
, empty, since no run exists yet.waitingFor - Loop over
again, taking each numbernums in order. Ifx holds no copy ofunplaced , a new run took it earlier, so skip it. Otherwise take one copy.x - If some run waits for
, extend it: one fewer run waits forx and one more waits forx .x + 1 - Otherwise, if
andx + 1 both have a free copy, start a new run: take one copy of each, and record a run that waits forx + 2 .x + 3 - If neither works, return
at once. When the loop places every number, returnfalse .true
The main
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:
[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]false
The line for [1, 2, 3, 4, 5, 5, 6, 7]truefalse
[1, 2]falsetrue
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
operations that take constant time on average.HashMap - Space: O(n), because
has one entry per distinct value and each number adds at most one new key tounplaced .waitingFor
Another greedy method that places items one at a time and stops as soon as one has nowhere to go is