Skip to content

Commit 8b69386

Browse files
committed
Add solution for Longest Consecutive Sequence
1 parent 5762ba2 commit 8b69386

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
# Intuition
3+
Sort array first, then compare every element with its previous one
4+
while counting consecutive ones.
5+
6+
# Approach
7+
1. sort
8+
2. initiate variables: max_count, current_count, previous_element_idx
9+
3. for n in nums:
10+
3-1. if n is nums[prev] + 1: current_count++
11+
elif n is smaller or bigger than nums[prev] + 1:
12+
update max_count and initiate current_count
13+
3-2. increase previous element index
14+
4. return max_count
15+
16+
# Complexity
17+
- Time complexity: O(N)
18+
19+
- Space complexity: O(1)
20+
"""
21+
22+
23+
class Solution:
24+
def longestConsecutive(self, nums: List[int]) -> int:
25+
nums.sort()
26+
max_count = 0
27+
count = 1
28+
prev = 0
29+
for n in nums[1:]:
30+
if n == nums[prev] + 1:
31+
count += 1
32+
elif n < nums[prev] or n > nums[prev] + 1:
33+
max_count = max(count, max_count)
34+
count = 1
35+
prev += 1
36+
return max(count, max_count) if len(nums) else 0

0 commit comments

Comments
 (0)