1
class Solution:
2

3
from collections import defaultdict
4

5
def isPossible(self, nums):
6
# If the length of the array is less than 3, it's not possible to create subsequences of length 3 or more.
7
if len(nums) < 3:
8
return False
9

10
# 'count' dictionary stores the frequency of each number in the input array.
11
count = defaultdict(int)
12

13
# 'tails' dictionary stores the number of subsequences that end at a certain number.
14
tails = defaultdict(int)
15

16
# Populate the 'count' dictionary with the frequency of each number.
17
for num in nums:
18
count[num] += 1
19

20
# Iterate through the input array.
21
for num in nums:
22
# If the count of the current number is 0, it means this number has already been used in a subsequence.
23
if count[num] == 0:
24
continue
25
# If there is a subsequence that ends with the current number minus 1,
26
# it means we can extend that subsequence by adding the current number.
27
elif tails[num - 1] > 0:
28
tails[
29
num - 1
30
] -= 1 # Decrease the count of the tails that end with the current number minus 1.
31
tails[
32
num
33
] += 1 # Increase the count of the tails that end with the current number.
34
# If there are enough numbers after the current number to form a subsequence,
35
# create a new subsequence starting with the current number.
36
elif count[num + 1] > 0 and count[num + 2] > 0:
37
count[num + 1] -= 1 # Decrease the count of the next number.
38
count[
39
num + 2
40
] -= 1 # Decrease the count of the number after the next number.
41
tails[
42
num + 2
43
] += 1 # Increase the count of the tails that end with the number after the next number.
44
else:
45
# If we can't extend an existing subsequence or start a new one, return False.
46
return False
47

48
# Decrease the count of the current number since it's used in a subsequence.
49
count[num] -= 1
50

51
# If the function successfully iterates through the entire array, return True.
52
return True

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0