Longest Consecutive Sequence

MediumHash Tables · Set Lookup🧩 Hashing & CountingLeetCode #128 ↗Updated

Problem

You get an unsorted integer array nums. Return the length of the longest run of values x, x+1, x+2, … that all appear in the array (in any positions). Duplicates count once. The intended solution runs in O(n) time.
Input[100,4,200,1,3,2]Output4 (1,2,3,4)
Input[0,3,7,2,5,8,4,6,0,1]Output9
Input[]Output0

0 ≤ n ≤ 105  ·  -109 ≤ nums[i] ≤ 109  ·  Required: O(n) time.

Try it yourself

Java
class Solution {
    public int longestConsecutive(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Only start counting from a number x whose predecessor x-1 is absent — it is a sequence start. Each run is then walked exactly once, so the total work is O(n) with a hash set.
PatternHashing & Counting

Instinct Need "have I seen this before?", "how many times?" or "group things that look alike"? Trade memory for O(1) lookups with a HashMap, HashSet or int[26].

Memory hack Don't search, remember - every element checks in at the front desk, and the desk answers instantly.

Open the Hashing & Counting guide →

Approaches

Brute ForceExtend Every Number with Linear Search

Time O(n3)Space O(1)

Treat every element as a possible start and keep asking “is x+1 in the array?” by scanning it. A run of length L costs L scans of O(n), and we may do this for all n starts.

Java
public int longestConsecutive(int[] nums) {
    int best = 0;
    for (int num : nums) {
        int cur = num, streak = 1;
        while (contains(nums, cur + 1)) {
            cur++;
            streak++;
        }
        best = Math.max(best, streak);
    }
    return best;
}
private boolean contains(int[] nums, int target) {
    for (int x : nums) if (x == target) return true;
    return false;
}

Correct and memory-free, but cubic — hopeless for n = 105.

At a glance

LevelApproachTimeSpace
Brute ForceExtend Every Number with Linear SearchO(n3)O(1)
BetterSort, then Count RunsO(n log n)O(log n)
OptimalHashSet — Grow Only from Sequence StartsO(n)O(n)
Common pitfalls
  • Starting a walk from every number (no num-1 check) — silently becomes O(n2).
  • Sorting version: not skipping duplicates resets the streak on [1,2,2,3].
  • Returning 1 for an empty array — the answer is 0.
Interview tips
  • Mention sorting first, then note it violates the O(n) requirement.
  • Justify O(n) with amortised analysis: each element is walked over at most once.
  • Union-Find also works (union x with x±1) — mention it as an alternative.
Pattern
Hash set + “start of run” check → finding consecutive runs in unsorted data in linear time.
My notes saved in this browser