Algo-Sim › Arrays & Hashing

Longest Consecutive Sequence

Medium · Arrays & Hashing · step through it in Java, Python and C++ on your own input

Find the length of the longest run of consecutive integers in an unsorted array, in O(n), with a hash set.

Problem

Given an unsorted integer array nums, return the length of the longest run of values x, x + 1, x + 2, … that are all present in the array. The values need not be adjacent in nums, and duplicates count once.

Constraints

Edge cases to test

Follow-up questions

Why is it O(n) when there is a loop inside the loop?
A run is only walked from its smallest value (the one with no x − 1 in the set), so each value is visited a constant number of times overall.
What if you can sort?
Sort and count runs, skipping equal neighbours: O(n log n) time, O(1) extra space.
What if numbers keep arriving?
Union-find over value neighbours (or a map from run ends to lengths): near O(1) amortized per insert.

Solution

Java

public int longestConsecutive(int[] nums) {
    Set<Integer> set = new HashSet<>();
    for (int x : nums) set.add(x);
    int best = 0;
    for (int x : set) {
        if (set.contains(x - 1)) continue;
        int length = 1;
        while (set.contains(x + length)) length++;
        best = Math.max(best, length);
    }
    return best;
}

Python

def longest_consecutive(nums):
    num_set = set(nums)
    best = 0
    for x in num_set:
        if x - 1 in num_set:
            continue
        length = 1
        while x + length in num_set:
            length += 1
        best = max(best, length)
    return best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int longestConsecutive(vector<int> &nums) {
        unordered_set<int> set = {};
        for (int x : nums)
            set.insert(x);
        int best = 0;
        for (int x : set) {
            if (set.count(x - 1))
                continue;
            int length = 1;
            while (set.count(x + length))
                length++;
            best = std::max(best, length);
        }
        return best;
    }
};

More Arrays & Hashing problems