Longest Consecutive Sequence
Problem
You are given an unsorted array of integers nums. Find the length of the longest run of consecutive integers that all appear in the array, regardless of their positions. For example, if 8, 9, 10, 11 are all present somewhere in the array, that run has length 4. Aim for linear time.
- The array may be empty and has at most 150,000 elements.
- Values can be large in either direction (magnitudes up to a billion), so an array indexed by value is not an option.
Examples
nums = [42, 11, 9, 12, 50, 10, 8]→5. The run8, 9, 10, 11, 12is present.nums = [-2, 6, 3, -1, 5, 4, 0, 1, 2, -2]→9. Every value from -2 through 6 appears; the duplicate -2 does not extend the run.nums = []→0. No elements, no run.
Hints
- Sorting makes runs obvious but costs O(n log n). What data structure gives O(1) "is value v present?"
- If you start extending a run from every element, you will do redundant work. Which elements are worth starting from?
- Only start from values whose predecessor
v - 1is absent; those are exactly the left ends of runs.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.