Longest Consecutive Sequence solution explained
The linear-time answer to Longest Consecutive Sequence puts every number in a hash set, then only starts counting from numbers whose predecessor is missing, because those are the first values of their runs. From each start it walks upward while the next integer is in the set, so every value is touched a constant number of times and the whole thing is O(n) on average.
By Evin JohnPublished 6 min read
Problem statement in our words
You receive integers in no particular order, possibly with repeats and negatives. Consider the distinct values as a set and find the longest stretch of consecutive integers that are all present. Report the length of that stretch. Position in the list does not matter at all, which is what separates this from subarray questions.
| List | Longest run | Length |
|---|---|---|
| [31, 4, 30, 2, 33, 3, 32] | 30, 31, 32, 33 | 4 |
| [5, 5, 6, 6, 7] | 5, 6, 7 | 3 (repeats add nothing) |
| [-2, 0, -1, 9] | -2, -1, 0 | 3 |
| [12] | 12 | 1 |
| [] | none | 0 |
Worth confirming: is the answer the length or the run itself, can the list be empty, and is O(n log n) acceptable or does the interviewer explicitly want linear time? Many versions of this question say linear time is required, which rules out the sort-based answer as the final one.
Why this one is a favorite
Most candidates find the sort-based solution quickly. The question is really about the second step: getting to linear time without sorting, and then defending the complexity. The nested while loop inside a for loop looks quadratic, and interviewers want to hear you explain why it is not. That explanation, an amortized argument about how often each value is visited, is the part that separates candidates.
Starting point: sort, then scan
Sort the numbers. Walk the sorted list keeping a current run length. If the next value equals the previous one, skip it. If it is exactly one more, extend the run. Otherwise, reset the run to one. Track the best run seen. Sorting dominates at O(n log n), and the scan is linear.
def longest_run_sorted(nums):
if not nums:
return 0
vals = sorted(nums)
best = run = 1
for prev, cur in zip(vals, vals[1:]):
if cur == prev:
continue
run = run + 1 if cur == prev + 1 else 1
best = max(best, run)
return bestThe duplicate skip matters. Without it, the second 6 in [5, 6, 6, 7] would count as a gap, reset the run, and the function would report 2 instead of 3.
Linear time with a set
Put every value into a hash set so membership checks are O(1) on average. A naive idea is to walk upward from every value, but then a run of length L gets walked L times, once from each of its members, which is quadratic for one long run. The fix is a single condition: only begin walking from x when x - 1 is not in the set. That makes x the smallest member of its run, so each run is walked exactly once.
def longest_run(nums):
present = set(nums)
best = 0
for x in present:
if x - 1 in present:
continue # not the start of a run
end = x
while end + 1 in present:
end += 1
best = max(best, end - x + 1)
return bestfunction longestRun(nums) {
const present = new Set(nums);
let best = 0;
for (const x of present) {
if (present.has(x - 1)) continue;
let end = x;
while (present.has(end + 1)) end += 1;
best = Math.max(best, end - x + 1);
}
return best;
}Why the nested loop is still linear
Count the work per value. Each distinct value is checked once by the outer loop. The inner while loop only runs from run starts, and it advances through the members of that one run. Runs do not overlap, so across the whole execution the inner loop takes at most one step per distinct value. Outer plus inner is at most about 2n set lookups, so the total is O(n) average time with O(n) extra space for the set.
Loop over the set, not the input list. If the list holds the same run start many times, say a hundred thousand copies of 1 followed by the values 2 to 100,000, looping over the list would walk the full run once per copy. Looping over the set visits each distinct start once.
How the options compare
| Approach | Time | Extra space | Comment |
|---|---|---|---|
| Walk up from every value, no start check | O(n²) worst case | O(n) | Quadratic on one long run |
| Sort, then scan | O(n log n) | O(n) or in place | Good first answer, easy to get right |
| Set with run-start check | O(n) average | O(n) | The expected final answer |
| Union-find over neighbors | Close to O(n) | O(n) | Works, but more code than needed |
Test inputs to keep handy
- Empty list returns 0, and a single value returns 1.
- All copies of one value, such as [8, 8, 8], returns 1.
- Negatives and zero in the same run.
- Two runs of equal length: either is fine, since only the length is reported.
- Values far apart, such as [1, 1000000], to show nothing depends on the range of values.
- In fixed-width languages, a run that ends at the largest integer, where end + 1 can overflow. Python and JavaScript numbers in normal ranges are safe.
Mistakes interviewers notice
- Dropping the start check and then claiming O(n).
- Iterating the original list instead of the set when duplicates are allowed.
- Treating the problem as a subarray question and keeping positions.
- Forgetting the duplicate skip in the sort-based scan.
- Allocating a boolean array indexed by value, which breaks on negatives and on huge ranges.
Talking through it
Fictional example
- Interviewer
- You have a while loop inside a for loop. Why is that not quadratic?
- Candidate
- Because the while loop only starts at a value whose predecessor is missing, which means it is the bottom of a run. Each run gets walked once, and runs do not share values.
- Candidate
- So over the whole function the inner loop moves at most once per distinct value. With the outer loop that is about two lookups per value, so linear on average with a hash set.
Neighboring problems
Group Anagrams is another case where a hash structure replaces sorting the whole input. For a different way to avoid repeated work across a sequence, Trapping Rain Water and Valid Palindrome both use pointers that only move inward. The Two Sum walkthrough shows the plain set or dictionary lookup this builds on, and the coding problems hub has the rest.
Rehearsing with Natively
This is a problem where the explanation matters as much as the code. Natively, a desktop app for Mac and Windows, transcribes a practice round so you can reread how you justified the nested loop, and it can read the prompt from a screenshot and offer an approach to check against yours once you are done. The AI assistant for coding interviews page covers how that works.
Questions people ask
How do you solve Longest Consecutive Sequence in O(n)?
Put every number in a hash set. For each value whose predecessor is not in the set, count upward while the next integer is present, and keep the longest count. Each value is visited a constant number of times.
Why only start counting where x - 1 is missing?
Because that value is the first of its run. Starting anywhere else would recount a run you will also count from its true start, which turns the loop quadratic on a long run.
Is sorting an acceptable answer?
Yes as a first answer. Sort, skip duplicates, and track the current run length in one scan, for O(n log n) time. Then explain how the set removes the sort.
How should duplicates be handled?
They do not extend a run. Iterate over the set rather than the original list so repeated values are not processed again and again.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
