Skip to content

Commit e018fc2

Browse files
committed
Arrays - medium - longest consecutive sequence implementation
1 parent a84f7ba commit e018fc2

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def longestConsecutive(self, nums: List[int]) -> int:
6+
7+
longest_range = 0
8+
mem = {}
9+
for i in nums:
10+
mem[i] = True
11+
12+
for i in nums:
13+
if not mem[i]:
14+
continue
15+
mem[i] = False
16+
current_length = 1
17+
next_val = i + 1
18+
prev_val = i - 1
19+
while prev_val in mem:
20+
mem[prev_val] = False
21+
current_length += 1
22+
prev_val -= 1
23+
while next_val in mem:
24+
mem[next_val] = False
25+
current_length += 1
26+
next_val += 1
27+
longest_range = max(longest_range, current_length)
28+
return longest_range

0 commit comments

Comments
 (0)