File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments