Browse curriculum

Longest Consecutive Sequence (LeetCode 128)

Longest Consecutive Sequence (LeetCode 128): find the length of the longest run of consecutive integers in an unsorted array in O(n) with a hash set.

Problem Understanding

Longest Consecutive Sequence: given an unsorted array of integers nums, return the length of the longest run of consecutive values (x, x+1, x+2, …) that all appear in the array. The run can use the values in any order of the array. The target is O(n) time.

Example: [100, 4, 200, 1, 3, 2] returns 4, for 1, 2, 3, 4.

Attempt 1: Sort, Then Scan

Sort the array and walk it, extending the current run while each value is one more than the previous (skipping duplicates). It is simple and correct, but the sort costs O(n log n). A naive alternative (for every value, count upward with a linear search for each next value) is O(n³) or O(n²) with a set.

Visualizing the Issue

With a set, counting upward from every value repeats work. In 1, 2, 3, 4, counting from 1 walks four values, from 2 walks three, from 3 two, from 4 one: the same run is walked four times. On a long run of n values that is O(n²).

The Intuition: Count Each Run Once, From Its Start

A value starts a run exactly when its predecessor is missing:

  1. Put every number in a hash set.
  2. For each value num in the set, if num - 1 is in the set, skip it: its run will be counted from the start.
  3. Otherwise count upward: num + 1, num + 2, … while each is in the set, and keep the longest length.

Every run is walked once, from its start, and every other value is rejected with one lookup: O(n) in total.

Longest Consecutive Sequence Visualization

[100, 4, 200, 1, 3, 2]

BUILD THE SET

set, sorted for display

1

2

•

3

•

4

•

100

200

num

:

Length

:

Best

0

 

Put the 6 numbers in a set: 6 distinct values. best = 0

Next

99 is not in the set: 100 starts a run. length = 1

Free preview: the first 5 of 14 steps

Array

The set's values are drawn in sorted order so runs show up as neighbours: the algorithm itself never sorts. Watch values with a predecessor get skipped, and each run fill in from its start; the longest run so far stays highlighted.

Longest Consecutive Sequence Dry Run

Input: [100, 4, 200, 1, 3, 2]: set {100, 4, 200, 1, 3, 2}

num num − 1 in set? Action best
100 no (99) run 100: 101 missing, length 1 1
4 yes (3) skip 1
200 no (199) run 200, length 1 1
1 no (0) run 1, 2, 3, 4: 5 missing, length 4 4
3 yes (2) skip 4
2 yes (1) skip 4

Return 4. The run 1..4 was walked once, starting at 1.

Longest Consecutive Sequence LeetCode Solution

Hash set, counting each run from its start.

Longest Consecutive Sequence Code
1var longestConsecutive = function(nums) {
2 const numSet = new Set(nums);
3 let best = 0;
4 for (const num of numSet) {
5 if (!numSet.has(num - 1)) {
6 let length = 1;
7 while (numSet.has(num + length)) {
8 length++;
9 }
10 best = Math.max(best, length);
11 }
12 }
13 return best;
14};

Longest Consecutive Sequence in Python, Java, C++, TypeScript and C

Longest Consecutive Sequence in Python
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        num_set = set(nums)
        best = 0
        for num in num_set:
            if num - 1 not in num_set:
                length = 1
                while num + length in num_set:
                    length += 1
                best = max(best, length)
        return best
Longest Consecutive Sequence in Java
class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> numSet = new HashSet<>();
        for (int num : nums) numSet.add(num);
        int best = 0;
        for (int num : numSet) {
            if (!numSet.contains(num - 1)) {
                int length = 1;
                while (numSet.contains(num + length)) {
                    length++;
                }
                best = Math.max(best, length);
            }
        }
        return best;
    }
}
Longest Consecutive Sequence in C++
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> numSet(nums.begin(), nums.end());
        int best = 0;
        for (int num : numSet) {
            if (!numSet.count(num - 1)) {
                int length = 1;
                while (numSet.count(num + length)) {
                    length++;
                }
                best = max(best, length);
            }
        }
        return best;
    }
};
Longest Consecutive Sequence in TypeScript
function longestConsecutive(nums: number[]): number {
    const numSet = new Set(nums);
    let best = 0;
    for (const num of numSet) {
        if (!numSet.has(num - 1)) {
            let length = 1;
            while (numSet.has(num + length)) {
                length++;
            }
            best = Math.max(best, length);
        }
    }
    return best;
}
Longest Consecutive Sequence in C
typedef struct {
    int key;
    UT_hash_handle hh; // uthash.h, available on LeetCode
} Entry;

static bool has(Entry *set, int key) {
    Entry *e;
    HASH_FIND_INT(set, &key, e);
    return e != NULL;
}

int longestConsecutive(int* nums, int numsSize) {
    Entry *set = NULL, *e, *tmp;
    for (int i = 0; i < numsSize; i++) {
        if (!has(set, nums[i])) {
            e = malloc(sizeof(Entry));
            e->key = nums[i];
            HASH_ADD_INT(set, key, e);
        }
    }
    int best = 0;
    HASH_ITER(hh, set, e, tmp) {
        if (!has(set, e->key - 1)) {
            int length = 1;
            while (has(set, e->key + length)) {
                length++;
            }
            if (length > best) best = length;
        }
    }
    return best;
}

Edge Cases & Common Mistakes

  • Empty array: the set is empty and the answer is 0.
  • Duplicates ([0, 0, 1]): the set collapses them; the answer is 2.
  • Negative numbers: nothing changes, -2, -1, 0 is a run of 3.
  • Counting from every value: correct but O(n²) on a long run. The num - 1 check is the whole optimisation.
  • Iterating nums instead of the set: with many duplicates of a run's start, the run is re-walked once per duplicate.

Summary

A hash set answers "is this neighbour present?" in O(1), which replaces sorting. The trick is to start counting only where a run begins: checking num - 1, so every run is walked exactly once.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Build a set

    Insert every number into a hash set; duplicates collapse.

  2. Start only at run starts

    For each value, skip it if value - 1 is in the set; otherwise it starts a run.

  3. Count the run

    From a start, count upward while the next value is in the set, and keep the longest length.

Frequently asked questions

How is Longest Consecutive Sequence solved in O(n) time?

Put every number in a hash set. A number starts a run only if num - 1 is not in the set; from each start, count upward while num + length is in the set. Every number is looked up a constant number of times, so the whole pass is O(n).


Why skip numbers whose predecessor is in the set?

If num - 1 is present, num sits inside a run that will be counted from its start. Counting from num as well would walk the same run again; for a sorted input of n values that turns the algorithm into O(n²).


Why not just sort the array?

Sorting and scanning for runs works but takes O(n log n) time. The hash set reaches O(n) by looking neighbours up instead of placing them next to each other.

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description