Split Array into Consecutive Subsequences — LeetCode 659 Python Solution
- Problem
- #659
- Pattern
- Heap / Priority Queue
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [1,2,3,3,4,5]
- Output
- true
- Explanation
- nums can be split into the following subsequences:
Python solution
class Solution:
def isPossible(self, nums: List[int]) -> bool:
d = defaultdict(list)
for v in nums:
if h := d[v - 1]:
heappush(d[v], heappop(h) + 1)
else:
heappush(d[v], 1)
return all(not v or v and v[0] > 2 for v in d.values())Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 659. Split Array into Consecutive Subsequences is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 659. Split Array into Consecutive Subsequences?
- LeetCode 659. Split Array into Consecutive Subsequences is rated Medium on LeetCode.
- What is the time complexity of LeetCode 659. Split Array into Consecutive Subsequences?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 659. Split Array into Consecutive Subsequences?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 659. Split Array into Consecutive Subsequences cover?
- LeetCode 659. Split Array into Consecutive Subsequences is tagged Greedy, Array, Hash Table and Heap (Priority Queue) on LeetCode.