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
Current: —
Length: —
Longest: —
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.
# ─── LONGEST CONSECUTIVE (LeetCode 128) ───
# 1. Define: longestConsecutive(nums)
#
# 2. Build set: num_set = set(nums); longest = 0
# 3. Loop: for num in num_set:
#
# if num - 1 not in num_set:
# current_num = num
# current_length = 1
# while current_num + 1 in num_set:
# current_num += 1
# current_length += 1
# longest = max(longest, current_length)
#
# Vars: num_set, longest, current_num, current_length
▼ your implementation ▼
Verify your solution: