The Problem

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

You must write an algorithm that runs in O(n) time.

A consecutive sequence is a set of numbers where each number is exactly one more than the previous. For example, [1, 2, 3, 4] is a consecutive sequence of length 4.

Interactive Visualization

Speed:
Original Array
Number Line
Current sequence: โ€”
Best so far: 0
Hash Set
Status
Press Step or Play to begin.
Code
fun longestConsecutive(nums: IntArray): Int {    val numSet = nums.toHashSet()    var best = 0    for (n in numSet) {        if (n - 1 !in numSet) { // start of seq            var length = 1            while (n + length in numSet) {                length++            }            best = maxOf(best, length)        }    }    return best}

How It Works

Key Insight

The trick is to only start counting from the beginning of each sequence. A number n is the start of a consecutive sequence if and only if n - 1 is not in the set. By skipping numbers that are in the middle of a sequence, we ensure each number is visited at most twice (once in the outer loop, once when extending), giving us O(n) total time.

The Algorithm

  • Build a set: Insert all numbers into a hash set for O(1) lookups.
  • For each number n in the set: Check if n - 1 exists. If it does, n is not the start of a sequence โ€” skip it.
  • If n is a sequence start: Extend by checking n + 1, n + 2, ... until we find a gap. Track the length.
  • Update best: After each sequence is fully extended, compare its length to the current best.

Complexity

Time O(n)
Space O(n)

Although there is a nested while inside the for loop, each number is the start of at most one sequence. Every number is extended through at most once across all iterations, so the total work is O(n). The hash set uses O(n) extra space.