Longest Consecutive Sequence
LeetCode 128 • Medium • Arrays & Hashing
Return the length of the longest consecutive elements sequence. Only start counting from sequence starts (num-1 not in set).
TimeO(n)each num visited at most twice
SpaceO(n)hash set
Ready
Press Play. Build a set for O(1) lookups. For each num, only count if num-1 not in set (sequence start). Extend forward, track longest.
TimeO(n)each num visited at most twice
SpaceO(n)set + call stack
Recursive: countFrom(num) — if num not in set return 0; return 1 + countFrom(num+1). Only call from sequence starts (num-1 not in set).
3
Practice until you don't need to look. Key: num-1 not in set → start of sequence; count forward.
PATTERN ▸ num-1 not in set → start of sequence O(n) · O(n)
① INIT
num_set = set(nums)
longest = 0
② LOOP
for num in num_set:
③ START OF SEQUENCE?
if num - 1 not in num_set:
current_num, current_length = num, 1
while current_num + 1 in num_set:
current_num += 1; current_length += 1
longest = max(longest, current_length)
④ RETURN
return longest
▼ your implementation ▼