Longest consecutive sequence

Find the length of the longest run of consecutive integers, in O(n), without sorting.

Time O(n)Space O(n)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Put every number into a hash set, then only start counting a run from a number that has no predecessor in the set (x - 1 is missing). Every run therefore gets counted exactly once, starting from its smallest member, which keeps the whole scan O(n) even though it looks nested.

Code

public static int LongestConsecutive(int[] a) {
    var set = new HashSet<int>(a);
    int best = 0;
    foreach (int x in set) {
        if (set.Contains(x - 1)) continue;
        int len = 1;
        while (set.Contains(x + len)) len++;
        best = Math.Max(best, len);
    }
    return best;
}
static int longestConsecutive(int[] a) {
    Set<Integer> set = new HashSet<>(); for (int x : a) set.add(x);
    int best = 0;
    for (int x : set) {
        if (set.contains(x - 1)) continue;
        int len = 1;
        while (set.contains(x + len)) len++;
        best = Math.max(best, len);
    }
    return best;
}
int longestConsecutive(const vector<int>& a) {
    unordered_set<int> set(a.begin(), a.end());
    int best = 0;
    for (int x : set) {
        if (set.count(x - 1)) continue;
        int len = 1;
        while (set.count(x + len)) len++;
        best = max(best, len);
    }
    return best;
}
def longest_consecutive(a: list[int]) -> int:
    nums = set(a)
    best = 0
    for x in nums:
        if x - 1 in nums: continue
        length = 1
        while x + length in nums: length += 1
        best = max(best, length)
    return best

Tips

In the .NET library

It looks like an O(n^2) nested loop, but across the whole run of the algorithm the inner while only ever advances through each number once, since a number is only ever visited from the start of its own run.