659. Split Array into Consecutive Subsequences
Problem
nums is sorted. Decide whether it can be split into subsequences that each consist of consecutive integers (each one more than the previous) and have length at least 3.
Example: [1,2,3,3,4,5] → true (1,2,3 and 3,4,5); [1,2,3,4,4,5] → false
Constraints: n ≤ 10⁴.
Greedy: each number first tries to extend a sequence ending at x−1 (ends[x−1] > 0); otherwise it must start a new sequence x, x+1, x+2 (needs those available). If neither works → false.
Complexity: O(n).
class Solution:
def isPossible(self, nums: List[int]) -> bool:
left, ends = Counter(nums), Counter()
for x in nums:
if not left[x]:
continue
left[x] -= 1
if ends[x - 1]:
ends[x - 1] -= 1
ends[x] += 1
elif left[x + 1] and left[x + 2]:
left[x + 1] -= 1
left[x + 2] -= 1
ends[x + 2] += 1
else:
return False
return True
assert Solution().isPossible([1, 2, 3, 3, 4, 5]) is True
assert Solution().isPossible([1, 2, 3, 3, 4, 4, 5, 5]) is True
assert Solution().isPossible([1, 2, 3, 4, 4, 5]) is False
class Solution {
public boolean isPossible(int[] nums) {
Map<Integer, Integer> left = new HashMap<>(), ends = new HashMap<>();
for (int x : nums) left.merge(x, 1, Integer::sum);
for (int x : nums) {
if (left.getOrDefault(x, 0) == 0) continue;
left.merge(x, -1, Integer::sum);
if (ends.getOrDefault(x - 1, 0) > 0) {
ends.merge(x - 1, -1, Integer::sum);
ends.merge(x, 1, Integer::sum);
} else if (left.getOrDefault(x + 1, 0) > 0 && left.getOrDefault(x + 2, 0) > 0) {
left.merge(x + 1, -1, Integer::sum);
left.merge(x + 2, -1, Integer::sum);
ends.merge(x + 2, 1, Integer::sum);
} else return false;
}
return true;
}
}
func isPossible(nums []int) bool {
left, ends := map[int]int{}, map[int]int{} // unused counts; subsequences ending at x
for _, x := range nums {
left[x]++
}
for _, x := range nums {
if left[x] == 0 {
continue
}
left[x]--
if ends[x-1] > 0 { // extend an existing subsequence
ends[x-1]--
ends[x]++
} else if left[x+1] > 0 && left[x+2] > 0 { // or start a new one of length 3
left[x+1]--
left[x+2]--
ends[x+2]++
} else {
return false
}
}
return true
}