Problem 659 · LeetCode 659(opens in a new tab)
Split Array into Consecutive Subsequences
MediumGreedy algorithms
You are given an integer array nums sorted from smallest to largest; values may repeat. Decide whether you can hand out every element to some number of chains so that each chain is a run of consecutive integers (each one exactly 1 more than the one before) and every chain has at least 3 elements.
Each element goes into exactly one chain, and a chain keeps the elements in their original order. Return true if such a split exists, and false otherwise.
Example 1
Input: nums = [2, 3, 4, 5, 5, 6, 7] Output: true Why: chains [2, 3, 4, 5] and [5, 6, 7]
2 more examples and the constraints
Example 2
Input: nums = [-2, -1, 0, 0, 1, 1, 2, 2] Output: true Why: chains [-2, -1, 0, 1, 2] and [0, 1, 2]
Example 3
Input: nums = [6, 7, 8, 8, 9] Output: false Why: one chain gets 6, 7, 8; the other 8 and the 9 make only 2
Constraints
- 1 ≤ nums.length ≤ 10,000
- −1,000 ≤ nums[i] ≤ 1,000
- nums is sorted in non-decreasing order
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Extend the shortest chainO(n log n)
- Greedy: extend first, else start threeO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 numbers | Verdict |
|---|---|---|---|
| Extend the shortest chain | O(n log n) | Passes; heap per end value | |
| Greedy: extend first | O(n) | Best; two maps |
n = length of nums.
Edge cases to test
- Fewer than 3 numbers. No chain can be long enough: [5] and [3, 4] are false.
- Repeated values only. [9, 9, 9] cannot form a run, because each chain needs different values.
- A gap. [1, 2, 4, 5, 6] is false: 1 and 2 cannot reach 3.
- Parallel chains. [0, 0, 0, 1, 1, 1, 2, 2, 2] is three chains of [0, 1, 2].
- Negative values. Maps handle them directly; an array would need an offset.
Common mistakes
- Starting a new chain before trying to extend an old one, which wastes x + 1 and x + 2.
- Starting a chain with x alone and checking lengths later, which misses the moment it fails.
- Forgetting to skip numbers that an earlier chain already used.
How to talk through it
- 1Clarify. Is nums sorted? Must every element be used? Is length 3 the minimum?
- 2Think in chains. Each number either extends a chain that ends at x − 1 or starts a new one.
- 3Pick the greedy. Extending is never worse; a new chain must grab x + 1 and x + 2 at once.
- 4Code two maps. count for unplaced values, tails for where finished chains end.
- 5Test out loud. Run [6, 7, 8, 8, 9] and [1, 2, 3, 4, 5, 5, 6, 7].
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?