Practice · 01 Unsorted Arrays: Hashing · 4/4

Longest Consecutive Sequence

The longest run of consecutive numbers, in O(n) without sorting.

MediumLeetCode #128
Solve on LeetCode ↗

Understand the problem

A family of several people wants to sit together on a flight. The booking system gives you the seat numbers still free in one row of a wide aircraft, in no particular order: [100, 4, 200, 1, 3, 2]. What's the longest run of free seats with consecutive numbers? Here it's 1, 2, 3, 4: four seats side by side.

The problem, stripped of the plane:

Given an unsorted array of integers nums, return the length of the longest sequence of consecutive values (like 1, 2, 3, 4). The values don't need to be next to each other in the array. Your algorithm must run in O(n) time.

InputOutputThe run
[100, 4, 200, 1, 3, 2]41, 2, 3, 4
[0, 3, 7, 2, 5, 8, 4, 6, 0, 1]90 to 8 (the second 0 adds nothing)
[1, 0, 1, 2]30, 1, 2
[]0no numbers, no run

The limits on LeetCode: 0 to 100,000 numbers, each between -10⁹ and 10⁹.

Brute force first

For every number x, count upwards: is x + 1 in the array? x + 2? Stop at the first missing one. Searching the array each time is a full scan.

int longestConsecutiveBrute(const vector<int>& nums) {
    int best = 0;
    for (int x : nums) {
        int length = 1;
        while (find(nums.begin(), nums.end(), (long long)x + length) != nums.end())  // O(n) search
            length++;
        best = max(best, length);
    }
    return best;
}

That's up to n starting points, each walking up to n steps, each step scanning n values: O(n³) in the worst case. For 100,000 numbers that's hopeless.

A better middle step: sort first

Sort the numbers, then walk once: if a number is exactly one more than the previous, the run grows; if it's equal, skip it (a duplicate); otherwise a new run starts.

int longestConsecutiveSorted(vector<int> nums) {   // by value: sorts a copy
    if (nums.empty()) return 0;
    sort(nums.begin(), nums.end());
    int best = 1, run = 1;
    for (size_t i = 1; i < nums.size(); i++) {
        if (nums[i] == nums[i - 1]) continue;      // duplicate: run neither grows nor breaks
        run = ((long long)nums[i] == (long long)nums[i - 1] + 1) ? run + 1 : 1;
        best = max(best, run);
    }
    return best;
}

O(n log n): fast enough to pass on LeetCode, but it breaks the problem's O(n) rule. In an interview, this is a good second answer, and the interviewer will ask for the last step.

See it in a diagram

Put every number in a hash set, so "is y there?" is O(1). Now, the brute force wasted work by counting the same run from every member: from 1 it walks 1-2-3-4, from 2 it walks 2-3-4 again, and so on. The fix: only start counting from the beginning of a run, a number whose left neighbour x - 1 is not in the set.

the set, laid out on a number line012345…1002001start1: is 0 in the set? no → 1 starts a runwalk up: 2, 3, 4 are there, 5 is not → length 42, 3, 4: their left neighbour is in the set → skip, never walked twice100 and 200 start runs of length 1every value is checked ≤ 2 times → O(n)
The set from [100, 4, 200, 1, 3, 2] on a number line. 1 has no 0 to its left, so it starts a run and walks up through 2, 3 and 4: length 4. 2, 3 and 4 each have a left neighbour, so they're skipped. 100 and 200 start runs of length 1.

Every run is walked exactly once, from its start.

Spot the pattern

The hashing signal again: unsorted, and you need "is this value present?" fast. What's new is the guard: before doing expensive work from an element, check a cheap condition (x - 1 absent) that makes sure the work is done once per group instead of once per member.

That "only start from the beginning" idea comes back often: counting islands only from an unvisited cell, building chains only from a head node. Whenever many elements would redo the same walk, find the one element that should own it.

The optimal solution

  1. Put all numbers into a set present (this also removes duplicates).
  2. For each x in the set:
    • if x - 1 is in the set, skip it: it's in the middle of a run;
    • otherwise, walk x + 1, x + 2, … while they're in the set, and count the length.
  3. Keep the longest length seen. Return it (0 for an empty input).

Code in 6 languages

Each program runs the first two examples and the empty array.

#include <algorithm>
#include <cstdio>
#include <unordered_set>
#include <vector>
using namespace std;

int longestConsecutive(const vector<int>& nums) {
    unordered_set<long long> present(nums.begin(), nums.end());
    int best = 0;
    for (long long x : present) {                  // the set, so each value once
        if (present.count(x - 1)) continue;        // not a start: x - 1 will count this run
        int length = 1;
        while (present.count(x + length)) length++; // walk up from the start
        best = max(best, length);
    }
    return best;
}

int main() {
    vector<vector<int>> tests = {{100, 4, 200, 1, 3, 2}, {0, 3, 7, 2, 5, 8, 4, 6, 0, 1}, {}};
    for (auto& nums : tests) {
        printf("[");
        for (size_t i = 0; i < nums.size(); i++) printf(i ? ", %d" : "%d", nums[i]);
        printf("] -> %d\n", longestConsecutive(nums));
    }
}

All six print:

[100, 4, 200, 1, 3, 2] -> 4
[0, 3, 7, 2, 5, 8, 4, 6, 0, 1] -> 9
[] -> 0
  • C++, Java and C# store the values as 64-bit numbers so that x + 1 can't overflow when x is the largest 32-bit integer. Python, JavaScript and Go don't need this.
  • Every version loops over the set, not over nums. The edge-case section shows why that matters.

Time and space complexity

It looks like a loop inside a loop, so it's tempting to call it O(n²). Count the work per value instead:

  • every value is checked once as a possible start (one x - 1 lookup), and
  • every value is stepped onto at most once by a walk, because only the run's start walks it.

So the total is about 2n lookups: O(n) time on average. The set holds up to n values: O(n) space.

ApproachTimeExtra space
Brute force, searching the arrayO(n³)O(1)
Sort, then one walkO(n log n)O(1) to O(n)
Hash set, walk only from startsO(n) averageO(n)

Edge cases and common mistakes

  • Empty input: return 0, not 1. Start best at 0.
  • Duplicates: [1, 2, 2, 3] has a run of length 3. The set drops the extra 2; in the sorted version, equal neighbours must be skipped, not treated as a break.
  • Looping over nums instead of the set: with many copies of a start value, like [1, 1, 1, …, 1, 2, 3, …, 50000], every copy of 1 is a start and walks the whole run again. That's O(n²). Looping over the set visits each value once.
  • Forgetting the start check: walking up from every value works but is O(n²) on an input like 1, 2, …, n.
  • Overflow: x + 1 when x is 2,147,483,647 overflows a 32-bit int in C++, Java and C#. Use a 64-bit type, or stop at the maximum value.
  • Negative numbers: nothing special, -3, -2, -1, 0 is a run of 4.

Where it's used in real apps

  • Seat maps: finding the longest block of free consecutive seats for a group booking on a flight or a long-distance bus.
  • Streaks: a fitness or language app stores the days you were active as a set of day numbers; your longest streak is exactly this problem.
  • Spotting gaps in sequence numbers: message queues and databases number their records; the runs between missing numbers show which ranges arrived intact and which need to be fetched again.
  • Free time slots: a calendar marks busy 15-minute slots; the longest run of free slot numbers is the longest meeting you can book.

Quick quiz

1. Why only start counting from a number whose

x - 1 is missing? Such a number is the first value of its run. Starting only there means every run is walked exactly once. Starting from every member would walk the same run again and again, which is O(n²).

2. There's a

while loop inside a for loop. Why is it still O(n)? The while loop only runs from run starts, and each value belongs to exactly one run, so across the whole program each value is stepped onto at most once. Plus one start check per value: about 2n lookups in total.

3. Why loop over the set rather than the original array?

The array can hold the same start value many times. Each copy would pass the start check and walk the whole run again. The set has each value once.

4. The input is already sorted. Is there anything better than the hash set?

Yes: one pass comparing each value with the previous one gives O(n) time and O(1) extra space, with no set at all.

5. How would you return the run itself, not just its length?

Along with the best length, remember the start value that produced it. The run is start, start + 1, …, start + length - 1.

Solved it yourself and understood the optimal approach? Mark it to track your progress.