#659

Split Array into Consecutive Subsequences

Medium
ArrayHash TableGreedyHeap (Priority Queue)Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a greedy approach with a HashMap to track the counts of elements and to build subsequences efficiently. This ensures that we can quickly determine if we can form valid subsequences of length 3 or more.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the frequency of each number in the array using a HashMap.
  2. 2Step 2: For each number in the array, attempt to build a subsequence starting from that number.
  3. 3Step 3: If a number can be added to an existing subsequence, do so; otherwise, create a new subsequence if possible.
  4. 4Step 4: Ensure that each subsequence has at least 3 elements.
solution.py22 lines
1# Full working Python code
2from collections import Counter
3
4def can_split(nums):
5    count = Counter(nums)
6    end = Counter()
7
8    for num in nums:
9        if count[num] == 0:
10            continue
11        count[num] -= 1
12
13        if end[num - 1] > 0:
14            end[num - 1] -= 1
15            end[num] += 1
16        elif count[num + 1] > 0 and count[num + 2] > 0:
17            count[num + 1] -= 1
18            count[num + 2] -= 1
19            end[num + 2] += 1
20        else:
21            return False
22    return True

Complexity note: The complexity is O(n) because we traverse the array a constant number of times, and the space complexity is O(n) due to the HashMap used for counting.

  • 1Each subsequence must be consecutive and of length at least 3.
  • 2Using a greedy approach with a HashMap allows efficient tracking of subsequences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.