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:
Return true
if you can split the array according to the above conditions, or false
otherwise.
nums
?
frequency
) to keep track of the frequency of each element in nums
.appendfreq
) to track how many consecutive subsequences can be extended with the current element.nums
.
False
if unable to meet the above conditions, otherwise return True
.def isPossible(nums):
from collections import defaultdict
# Frequency hashmap to count the occurrences of each number
frequency = defaultdict(int)
# Appendfreq hashmap to track the possibility of appending the current number to an existing subsequence
appendfreq = defaultdict(int)
for num in nums:
frequency[num] += 1
for num in nums:
if frequency[num] == 0:
continue
# If we can append num to an existing subsequence ending in num-1
if appendfreq[num - 1] > 0:
appendfreq[num - 1] -= 1
appendfreq[num] += 1
# If not, try to create a new subsequence num, num+1, num+2
elif frequency[num + 1] > 0 and frequency[num + 2] > 0:
frequency[num + 1] -= 1
frequency[num + 2] -= 1
appendfreq[num + 2] += 1
else:
return False
frequency[num] -= 1
return True
nums
. We make a single pass through nums
to build the frequency
hashmap and another pass to try and build/append the subsequences.frequency
and appendfreq
hashmaps.This approach ensures an efficient check for forming necessary subsequences while adhering to the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?