Longest Consecutive Sequence

Medium ArrayHash Set

Problem

Given an unsorted array of integers, return the length of the longest run of consecutive integers — the values must form a k, k+1, k+2, … run, but they may appear in any order in the array. Aim for O(n).

Example 1 Input: nums = [100,4,200,1,3,2] Output: 4 Explain: 1, 2, 3, 4
Example 2 Input: nums = [0,3,7,2,5,8,4,6,0,1] Output: 9
Example 3 Input: nums = [] Output: 0

Constraints

Approach — Hashing & Counting

This is a Hashing & Counting problem. The idea: store what you've seen in a hash map for O(1) lookups, trading a little space to avoid a nested scan. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(n) space.

Solution code

Python

class Solution:
    def longestConsecutive(self, nums):
        s = set(nums)
        best = 0
        for x in s:
            if x - 1 not in s:
                y = x
                while y + 1 in s:
                    y += 1
                best = max(best, y - x + 1)
        return best

Java

import java.util.HashSet;
import java.util.Set;

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int n : nums) set.add(n);
        int best = 0;
        for (int n : set) {
            if (!set.contains(n - 1)) {
                int cur = n, run = 1;
                while (set.contains(cur + 1)) { cur++; run++; }
                best = Math.max(best, run);
            }
        }
        return best;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Longest Consecutive Sequence interactively → ← All solutions