Skip to content

Commit b9b9d91

Browse files
committed
longest consecutive sequence solution
1 parent 6d0b022 commit b9b9d91

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Leetcode 128: https://leetcode.com/problems/longest-consecutive-sequence/
2+
# Goal: Given an unsorted array of integers nums,
3+
# return the length of the longest consecutive elements sequence.
4+
# Constraints:
5+
# - Unsorted array
6+
# - Must run in O(n) time
7+
# - Duplicates exist
8+
# Approach:
9+
# - Use a variable `longest=0` to track the length of the longest sequence.
10+
# - Convert nums into a hash set to check numbers in O(1).
11+
# - Iterate the nums.
12+
# - Use variables `currentL=1` to track the length of current sequence
13+
# and `j=1` to represent the distance from the current number.
14+
# - For checking larger numbers, do current num + j
15+
# and for checking smaller numbers, do current num - j
16+
# - Iterate through the set while consecutive number exists in the set.
17+
# If it founds the number, remove it from the set and update currentL & j.
18+
# - Update longest with the mximum length.
19+
# - Return longest.
20+
# Time complexity: O(n)
21+
# - Each number is removed from the set
22+
# Space complexity: O(n)
23+
# - Using a set. n -> size of the nums
24+
class Solution:
25+
def longestConsecutive(self, nums: List[int]) -> int:
26+
longest = 0
27+
s = set(nums)
28+
29+
for c in nums:
30+
currentL = 1
31+
j = 1
32+
33+
while c+j in s:
34+
s.remove(c+j)
35+
currentL += 1
36+
j += 1
37+
38+
j = 1
39+
while c-j in s:
40+
s.remove(c-j)
41+
currentL += 1
42+
j += 1
43+
44+
longest = max(longest, currentL)
45+
46+
return longest

0 commit comments

Comments
 (0)