Problem Statement
Longest Consecutive Sequence
You are given a list of whole numbers in no particular order. A consecutive sequence is a run of numbers that go up by one each time, like 1, 2, 3, 4. Your job is to find the longest such run hiding in the list and return how many numbers are in it. The catch is speed: you must do it in O(n) time, which means you get to look at the data only a small fixed number of times, not sort it or search it over and over. The tool that makes this possible is a hash set. A hash set is like a guest list at a door: you can ask "is this name on the list?" and get an instant yes or no, no matter how long the list is. We put every number on the list, then for each number we ask whether it is the start of a run (is the number just below it missing?), and if it is, we count forward to see how long the run goes.
Signals to notice
Brute force first
Sort and scan for consecutive runs. Sorting is overkill for this problem. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.
The key insight
Put all numbers in a hash set. For each number that's a sequence START (n-1 not in set), count consecutive numbers going up. Track the longest run. — each number is visited at most twice. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on nums=[100,4,200,1,3,2]
Build set={100,4,200,1,3,2}; longest=0
num=100: 99 not in set -> START; 101 not in set, length=1; longest=1
num=4: 3 IS in set -> not a start, skip
num=200: 199 not in set -> START; 201 not in set, length=1; longest=1
num=1: 0 not in set -> START; 2,3,4 in set -> length=4; longest=4
num=3: 2 IS in set -> skip
num=2: 1 IS in set -> skip
Loop done -> return longest=4What must stay true
Only start counting from the BEGINNING of a sequence (where n-1 doesn't exist in the set). This ensures each element is part of exactly one count, giving total. If that remains true after every update, the rest of the reasoning has a stable place to stand.
Shape of the loop
set = hashset(nums); longest = 0
for num in set:
if num - 1 not in set: # only start at a sequence beginning
length = 1
while num + length in set: length += 1
longest = max(longest, length)
return longestPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Starting a count from every number — that's. The key optimization is skipping numbers that aren't sequence starts. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.