Longest Consecutive Sequence
LeetCode 128 · Medium · solution, intuition & step-by-step walkthrough
Only expand from run starts (num − 1 not in set).
This is how I solved Longest Consecutive Sequence (LeetCode 128), a medium problem from the Hashing / Anagram pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Put everything in a set. A number only starts a run if num − 1 isn't present; from each such start, count upward while the next number exists. Each number is visited by at most one run, so the whole thing is linear.
Approach
- 1
Build a set (removes duplicates, O(1) lookups).
- 2
For each num with no predecessor, walk num+1, num+2, … counting length.
- 3
Track the longest run.
How I solved it
Hash set + run startsPythonO(n) time · O(n) space
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if not nums:
return 0
unique_elenents = set(nums) #remove duplicates
max_length = 1 #single element
for num in unique_elenents:
if num-1 not in unique_elenents:
length = 1
while num+1 in unique_elenents:
num = num+1
length+=1
max_length=max(max_length,length)
return max_lengthLongest Consecutive Sequence — FAQ
What is the intuition behind Longest Consecutive Sequence?
Put everything in a set. A number only starts a run if num − 1 isn't present; from each such start, count upward while the next number exists. Each number is visited by at most one run, so the whole thing is linear.
How do you solve Longest Consecutive Sequence (LeetCode 128)?
1. Build a set (removes duplicates, O(1) lookups). 2. For each num with no predecessor, walk num+1, num+2, … counting length. 3. Track the longest run.
What is the time and space complexity of Longest Consecutive Sequence?
Time: O(n). Space: O(n). (Accepted approach: Hash set + run starts.)
What are common mistakes in Longest Consecutive Sequence?
Without the 'is it a start?' check the algorithm degrades to O(n²). Empty input returns 0.