TRT
Sign in
mediumFoundationsLeetCode#hash set#start of a run

Longest consecutive sequence

Find the length of the longest run of consecutive integers in an unsorted array in O(n), using a hash set and starting only at the beginning of each run.

The Runtime Theory Team1 min read
Taught inHash maps in your languagePython, Java, JavaScript, Go, C++ and Rust all ship a hash map. They differ in how they resolve collisions and what they promise about order, and they share the same traps.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [100, 4, 200, 1, 3, 2]

out4

innums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]

out9

innums = []

out0

Given an unsorted array of integers, return the length of the longest sequence of consecutive values, such as 1, 2, 3, 4. Your solution must run in O(n) time.

Before you code

Sorting gives O(n log n). For O(n), put every value in a hash set, so "is x + 1 present?" costs O(1) on average. The trap is walking a run from every element in it, which is O(n²) on an input like 1, 2, …, n.

Hints

  1. Only start counting at x if x - 1 is not in the set: that makes x the first value of its run.
  2. From a run's start, count upward while x + 1 is in the set.
  3. Each value is visited at most twice, once in the main loop and once while counting its run, so the total is O(n).
  4. Duplicates don't matter, because the set removes them.

Production & complexity notes

When solving Longest consecutive sequence on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Hash maps in your language to reinforce the underlying pattern.

What it practices

Using a hash set as an O(1) membership test, from Hash maps in your language.

Not started

Sign in to save your learning progress.

Sign in to save