Split Array into Consecutive Subsequences - Problem

You are given an integer array nums that is sorted in non-decreasing order. Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true:

  • Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).
  • All subsequences have a length of 3 or more.

Return true if you can split nums according to the above conditions, or false otherwise.

A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,3,4,5]
Output: true
💡 Note: Can split into [1,2,3] and [3,4,5], both consecutive sequences of length ≥ 3
Example 2 — Cannot Split
$ Input: nums = [1,2,3,3,4,4,5,5]
Output: true
💡 Note: Can split into [1,2,3] and [3,4,5] and [4,5] - wait, [4,5] has length 2, so actually can split into [1,2,3,4,5] and [3,4,5]
Example 3 — Impossible Case
$ Input: nums = [1,2,3,4,4,5]
Output: false
💡 Note: Cannot form valid consecutive subsequences - one 4 would be left alone or in length-2 sequence

Constraints

  • 1 ≤ nums.length ≤ 104
  • -1000 ≤ nums[i] ≤ 1000
  • nums is sorted in non-decreasing order

Visualization

Tap to expand
Split Array into Consecutive Subsequences INPUT Sorted Array nums[] 1 2 3 3 4 5 0 1 2 3 4 5 Two Hash Maps: freq 1: 1 2: 1 3: 2, 4: 1, 5: 1 need Tracks what number is needed next Conditions: - Consecutive sequences - Length >= 3 nums = [1,2,3,3,4,5] ALGORITHM STEPS 1 Build freq map Count occurrences of each num 2 Iterate through nums Process each element greedily 3 Extend or Start New Prefer extending existing seq 4 Validate sequences Return false if can't place num Processing Order num=1: start seq [1,_,_] num=2: extend [1,2,_] num=3: extend [1,2,3] OK num=3: start new [3,_,_] num=4: extend [3,4,_] num=5: extend [3,4,5] OK FINAL RESULT Valid Subsequences Found: Sequence 1 1 2 3 Sequence 2 3 4 5 [OK] All consecutive [OK] Length >= 3 [OK] All nums used Output: true Key Insight: Use greedy approach with two hash maps: 'freq' tracks available numbers, 'need' tracks what numbers are needed to extend existing sequences. Always prioritize extending an existing sequence over starting a new one. This ensures we maximize sequence lengths and minimize the number of sequences needed. TutorialsPoint - Split Array into Consecutive Subsequences | Greedy with Two Hash Maps
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
28.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen