Skip to content

Commit b4cb47c

Browse files
pmjuupmjuu
authored andcommitted
feat: solve longest-consecutive-sequence
1 parent 4a27dad commit b4cb47c

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from typing import List
2+
3+
class Solution:
4+
def longestConsecutive(self, nums: List[int]) -> int:
5+
# Convert to set for O(1) lookups
6+
num_set = set(nums)
7+
longest_length = 0
8+
9+
for num in num_set:
10+
# Only start counting if num is the start of a sequence
11+
if num - 1 not in num_set:
12+
current_num = num
13+
current_length = 1
14+
15+
# Count the length of the sequence
16+
while current_num + 1 in num_set:
17+
current_num += 1
18+
current_length += 1
19+
20+
longest_length = max(longest_length, current_length)
21+
22+
return longest_length

0 commit comments

Comments
 (0)