Skip to content

Commit 91e2247

Browse files
committed
- Solution for "Longest Consecutive Sequence #240".
1 parent 192ef04 commit 91e2247

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(n), n = len(set_nums) = The number of unique numbers.
6+
- Space Complexity: O(n)
7+
"""
8+
def longestConsecutive(self, nums: List[int]) -> int:
9+
set_nums = set(nums)
10+
longest = 0
11+
12+
for num in set_nums:
13+
if num - 1 not in set_nums:
14+
# Only check for the start number
15+
cnt = 1
16+
next_num = num + 1
17+
while next_num in set_nums:
18+
cnt += 1
19+
next_num += 1
20+
longest = max(longest, cnt)
21+
22+
return longest
23+
24+
tc = [
25+
([100,4,200,1,3,2], 4),
26+
([0,3,7,2,5,8,4,6,0,1], 9),
27+
([1,0,1,2], 3)
28+
]
29+
30+
for i, (nums, e) in enumerate(tc, 1):
31+
sol = Solution()
32+
result = sol.longestConsecutive(nums)
33+
print(f"TC {i} is Passed!" if result == e else f"TC {i} is Failed!, Expected: {e}, Result: {result}")

0 commit comments

Comments
 (0)