File tree 1 file changed +36
-0
lines changed
1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Longest Consecutive Sequence
2
+ # https://www.github.com/JehanPatel
3
+
4
+ # Logic behind the question
5
+
6
+ # nums = [2, 3, 1, 4, 5]
7
+ # 1. num = 2
8
+ # 1 is present -> Don't run the inner loop
9
+ # 2. num = 3
10
+ # 2 is present -> Don't run the inner loop
11
+ # 3. curr_num = 1
12
+ # 0 is not present -> Run the inner loop
13
+ # a. curr_num = 1, curr_len = 1, while condition: True
14
+ # b. curr_num = 2, curr_len = 2, while condition: True
15
+ # c. curr_num = 3, curr_len = 3, while condition: True
16
+ # d. curr_num = 4, curr_len = 4, while condition: True
17
+ # e. curr_num = 5, curr_len = 5, while condition: False
18
+
19
+ # Optimal Code
20
+
21
+ class Solution :
22
+ def longestConsecutive (self , nums : List [int ]) -> int :
23
+ max_len = 0
24
+ num_set = set (nums )
25
+ for num in nums :
26
+ if num - 1 not in num_set :
27
+ curr_num = num
28
+ curr_len = 1
29
+ while curr_num + 1 in num_set :
30
+ curr_num += 1
31
+ curr_len += 1
32
+ max_len = max (max_len , curr_len )
33
+ return max_len
34
+
35
+ # Time and Space complexity = o(n)
36
+ # refer to leetcode discussion tab for further clarification.
You can’t perform that action at this time.
0 commit comments