Skip to content

Commit 033f632

Browse files
committed
Update question 128.
1 parent eeec425 commit 033f632

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

leetcode/hard/128_longest_consecutive_sequence.md

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,26 +6,23 @@
66
- N = Number of elements in array
77

88
The most intuitive solution is to sort the array, then iterate each number to find the longest range.
9-
Hoever, that would be N(log(N)) run-time.
9+
However, that would be N(log(N)) run-time.
1010

1111
To improve the run-time, we can store all the numbers into a set, then check if the left(n-1) and right(n+1) numbers are in the set.
12-
However, the run-time would be poor(O(N^2)), you would need a visited set to avoid traversing left and right for each number in the set to get O(N).
12+
However, the run-time would be poor, O(N^2), you would need a visited set to avoid traversing left and right for each number in the set to get O(N).
1313

1414
You can further improve the space complexity by only starting at either the left-most number or the right-most number.
1515
That would mean you just traverse only in one direction, avoiding the need of a visited set.
1616

1717
```
1818
class Solution:
1919
def longestConsecutive(self, nums: List[int]) -> int:
20-
if len(nums) == 0:
21-
return 0
22-
num_set = set(nums)
23-
longest_range = 0
24-
for n in num_set:
25-
if n-1 not in num_set: # beginning of a range
26-
curr_n = n
27-
while curr_n+1 in num_set:
28-
curr_n += 1
29-
longest_range = max(longest_range, curr_n-n)
30-
return longest_range+1
20+
num_set, longest_length = set(nums), 0
21+
for n in nums:
22+
if n-1 not in num_set: # left-most number
23+
length, curr = 0, n
24+
while curr in num_set:
25+
curr, length = curr+1, length+1
26+
longest_length = max(longest_length, length)
27+
return longest_length
3128
```

0 commit comments

Comments
 (0)