Skip to content

Commit 3ac748d

Browse files
Create split_array_consecutive_subsequences.py
1 parent 75b83d2 commit 3ac748d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution:
2+
def isPossible(self, nums: List[int]) -> bool:
3+
from collections import defaultdict
4+
occurrences, next_nums = defaultdict(int), defaultdict(int)
5+
for num in nums:
6+
occurrences[num] += 1
7+
for num in nums:
8+
if occurrences[num] == 0:
9+
continue
10+
# If next_nums contains the number, it is directly appendable to a sequence.
11+
# We "append" it to the sequence by incrementing the next number by 1.
12+
elif next_nums[num] > 0:
13+
next_nums[num] -= 1
14+
next_nums[num + 1] += 1
15+
# If the number + 1 and the number + 2 are both still in the occurrences hashmap,
16+
# We can create a new subsequence of length 3 and add the next number to next_nums.
17+
elif occurrences[num + 1] > 0 and occurrences[num + 2] > 0:
18+
occurrences[num + 1] -= 1
19+
occurrences[num + 2] -= 1
20+
next_nums[num + 3] += 1
21+
else:
22+
return False
23+
occurrences[num] -= 1
24+
return True

0 commit comments

Comments
 (0)