← Back to Algorithms, page 1

algorithms-0007 · Medium mid

Longest consecutive sequence: find the length of the longest run of consecutive integers in an unsorted list in O(n) time.

Put all values in a set. A value x starts a run only if x - 1 is not in the set; from each start, count upwards while x + 1, x + 2, ... exist. Each value is visited at most twice, once in the outer loop and once while extending a run, so the total is O(n) average time instead of O(n log n) for sorting.

Full answer

Problem

Given unsorted integers nums, return the length of the longest sequence of consecutive values (like 1, 2, 3, 4). Elements need not be adjacent in the list.

Example: [100, 4, 200, 1, 3, 2] gives 4 (the run 1, 2, 3, 4).

Constraints: 0 <= len(nums) <= 10^5, values may be negative, duplicates possible. Target O(n) time.

Brute force

For each value, count upward by checking membership with a linear scan: O(n^3), or O(n^2) with a set but without the start check (every element extends its own run).

Sorting gives a clean O(n log n) solution: sort unique values and count runs of neighbours that differ by 1.

Optimal approach

  1. values = set(nums) removes duplicates and gives O(1) lookups.
  2. For each x in the set, if x - 1 is in the set, skip it: it is in the middle of some run.
  3. Otherwise x is a run start. Count length while x + length is in the set.
  4. Track the maximum.

Why it works

Every run has exactly one start (its smallest value), and the inner loop only runs from starts. So each value is counted inside exactly one inner loop. Outer loop: n steps; all inner loops together: at most n steps. Total O(n).

Without the start check, a run of length L would be walked from each of its L elements, giving O(n^2) for one long run.

Complexity

O(n) average time (set operations are O(1) average), O(n) space.

Code

python
def longest_consecutive(nums):
    """Length of the longest run of consecutive integers, in O(n) average time."""
    values = set(nums)
    best = 0
    for x in values:
        if x - 1 not in values:          # x starts a run
            length = 1
            while x + length in values:
                length += 1
            best = max(best, length)
    return best


def longest_consecutive_sort(nums):
    """O(n log n) reference using sorting."""
    if not nums:
        return 0
    s = sorted(set(nums))
    best = cur = 1
    for a, b in zip(s, s[1:]):
        cur = cur + 1 if b == a + 1 else 1
        best = max(best, cur)
    return best


if __name__ == "__main__":
    for f in (longest_consecutive, longest_consecutive_sort):
        assert f([100, 4, 200, 1, 3, 2]) == 4
        assert f([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == 9
        assert f([]) == 0
        assert f([5]) == 1
        assert f([1, 2, 2, 3]) == 3
        assert f([-2, -1, 0, 10]) == 3
    print("all tests passed")

Save as a07_longest_consecutive.py and run python3 a07_longest_consecutive.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty input returns 0. Duplicates ([1, 2, 2, 3] gives 3, handled by the set). Negative numbers and zero. A single element gives 1. Very large gaps between values cost nothing extra, unlike an approach that allocates an array over the value range.

Pattern

Hash set membership plus "only start from the beginning of a run". The same start-detection trick prevents repeated work in many grouping problems; union-find is an alternative that also supports online insertions.

python
def longest_consecutive(nums):
    """Length of the longest run of consecutive integers, in O(n) average time."""
    values = set(nums)
    best = 0
    for x in values:
        if x - 1 not in values:          # x starts a run
            length = 1
            while x + length in values:
                length += 1
            best = max(best, length)
    return best


def longest_consecutive_sort(nums):
    """O(n log n) reference using sorting."""
    if not nums:
        return 0
    s = sorted(set(nums))
    best = cur = 1
    for a, b in zip(s, s[1:]):
        cur = cur + 1 if b == a + 1 else 1
        best = max(best, cur)
    return best


if __name__ == "__main__":
    for f in (longest_consecutive, longest_consecutive_sort):
        assert f([100, 4, 200, 1, 3, 2]) == 4
        assert f([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == 9
        assert f([]) == 0
        assert f([5]) == 1
        assert f([1, 2, 2, 3]) == 3
        assert f([-2, -1, 0, 10]) == 3
    print("all tests passed")

The O(n) set solution plus an O(n log n) sorting reference used in the same tests.

Complexity

Time: O(n) average. Space: O(n). The sorting reference is O(n log n) time and O(n) space for the deduplicated sorted copy.

By level

Fresher: Gives the sorting solution and then the set solution with the start check, explaining it on the example. Should test duplicates and negative numbers in the input.

Mid: Proves the O(n) bound and contrasts with the version that lacks the start check. Explains why each sequence is walked only from its start.

Senior: Discusses online variants with union-find or interval merging, memory limits for huge inputs and hash performance on adversarial values. Can explain why the average O(n) bound depends on hashing.

Key points

  • Use a set for O(1) membership
  • Only start counting from x where x - 1 is absent
  • Each value is touched a constant number of times
  • Sorting gives a simpler O(n log n) fallback
  • Duplicates are removed by the set

Common mistakes

  • Starting a count from every element and getting O(n^2)
  • Forgetting duplicates when using the sorting approach
  • Allocating an array over the whole value range
  • Returning the run itself when only the length was asked

Follow-ups

  • How would you return the actual sequence?
  • How would you support inserting numbers one at a time?
  • Can you solve it with union-find?

Tips

  • Mention the sorting solution first as a baseline
  • Explain the start check before coding
  • Justify O(n) with the "each value counted once" argument

Evaluation rubric

  • Correct O(n) algorithm
  • Clear argument for linear time
  • Handles duplicates and empty input
  • Mentions sorting baseline