Skip to content

Commit 24792fe

Browse files
committed
add solution: longest-consecutive-sequence
1 parent 89739e6 commit 24792fe

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'''
2+
# Leetcode 128. Longest Consecutive Sequence
3+
4+
keep time complexity O(n) by iterating through the set and accessing elements in O(1) time. ⚖️
5+
6+
## Time and Space Complexity
7+
```
8+
TC: O(n)
9+
SC: O(n)
10+
```
11+
12+
### TC is O(n):
13+
- iterating through the set. O(n)
14+
- accessing elements in the set. O(1)
15+
- while loop incrementing `current_num` while `current_num + 1 in nums_set`. O(1)
16+
17+
### SC is O(n):
18+
- creating a set from the list of numbers. O(n)
19+
'''
20+
21+
class Solution:
22+
def longestConsecutive(self, nums: List[int]) -> int:
23+
nums_set = set(nums) # O(n)
24+
longest_sequence = 0
25+
26+
for num in nums_set: # O(n)
27+
if (num - 1) not in nums_set:
28+
current_num = num
29+
current_sequence = 1
30+
31+
while current_num + 1 in nums_set: # O(1)
32+
current_num += 1
33+
current_sequence += 1
34+
35+
longest_sequence = max(current_sequence, longest_sequence)
36+
37+
return longest_sequence
38+

0 commit comments

Comments
 (0)