Problem Description
Given a sorted integer array nums, determine whether it is possible to split nums into one or more consecutive increasing subsequences, where each subsequence has a minimum length of 3. A valid consecutive subsequence means every number in the subsequence is exactly one more than its previous number.
Key Insights
- Use a greedy approach to form the subsequences.
- Utilize a frequency map to track how many times each number appears.
- Use an additional map to track how many subsequences ending with a certain number need to be extended.
- For each number, either extend an existing subsequence or start a new one if possible.
- If neither is possible, then it is not possible to form valid subsequences.
Space and Time Complexity
Time Complexity: O(n) where n is the number of elements in nums
Space Complexity: O(n) for storing the frequency and subsequence extension maps
Solution
We first count the frequency of every number in the array. Then, we iterate through the array and try to place each number:
- If a number is already part of an existing subsequence (tracked via the extension map), then extend that subsequence.
- Otherwise, check if the number can start a new subsequence (i.e., the next two consecutive numbers are available).
- If neither condition holds, return false immediately. This greedy algorithm ensures that subsequences are extended whenever possible, helping to avoid wasteful starts of new subsequences that might block later extensions.