Stage 1: Foundations·Arrays & Hashing
Medium#1286 min readHashingSetLeetCode

Longest Consecutive Sequence

Sequence-start HashSet scan

Only start counting from sequence beginnings. Think before you loop.

Published Apr 15, 2026

Problem

Given an unsorted array of integers nums, return the length of the longest consecutive-elements sequence.

The solution must run in O(n) time.

Input
nums = [100, 4, 200, 1, 3, 2]
Output
4
Explanation
The longest run is [1, 2, 3, 4].

Intuition

Sorting makes consecutive runs easy to detect, but sorting costs O(n log n), and the problem explicitly forbids that.

The trick is to stop asking "for every number, how long is the run containing it?" That repeats the same work.

Instead, only start counting from numbers that are actual sequence beginnings. A number x is a beginning if x - 1 is not present. Once you identify a beginning, walk upward until the run ends.

That "only start from beginnings" observation is what brings the complexity down to linear time.

Approach

HashSet + Start Detection

TimeO(n)
SpaceO(n)
Recommended

Insert every number into a set. Then for each number:

  • Skip it if x - 1 exists, because then it is inside a run, not the start.
  • Otherwise count x, x + 1, x + 2, ... until the run stops.
  • Track the maximum run length seen.
use std::collections::HashSet;

impl Solution {
    pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
        let set: HashSet<i32> = nums.into_iter().collect();
        let mut best = 0;

        for &x in &set {
            if set.contains(&(x - 1)) {
                continue;
            }

            let mut y = x;
            while set.contains(&(y + 1)) {
                y += 1;
            }

            best = best.max(y - x + 1);
        }

        best
    }
}
Rust · runnable

The inner while does not make this quadratic. Each number gets advanced through at most once across all runs, because only sequence starts enter that loop.

Edge cases

  • Empty array — answer is 0.
  • Duplicates — the set removes them automatically.
  • Negative numbers — consecutive logic works the same on signed integers.

Takeaway

Linear-time set solutions often come from deleting repeated work, not from clever constant factors.

For this problem, the set is necessary but not sufficient. The real insight is to count only from sequence starts.

More in Arrays & Hashing