◀ THE GRIND — ARRAYS & HASHING

Longest Consecutive Sequence

MEDIUM✓ CHIP-TIMEDLC #128 — FULL STATEMENT ↗

The drill: Find the length of the longest run of consecutive integers hiding inside an unsorted array, without sorting it first.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

An unsorted array of integers arrives, and hidden inside it somewhere is the longest unbroken run of consecutive values — the task is to report how long that run is.

The run doesn't need to appear in order inside the array itself; only that every integer from its lowest to its highest value exists somewhere in the array counts.

Sorting the array first would make runs easy to spot, but that already costs more than the target time budget allows — the drill is finding runs without ever ordering the input.

EX 01
nums = []
0
EMPTY ARRAY
EX 02
nums = [7]
1
SINGLE ELEMENT
EX 03
nums = [100, 4, 200, 1, 3, 2]
4
RUN 1-2-3-4 SCATTERED AMONG OUTLIERS
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Sorting makes consecutive runs trivial to spot in one scan, but sorting itself already costs more than linear time. What lets you find runs without an ordering step?

HINT 2 THE STRUCTURE

A hash set answers 'does this value exist' in O(1). Every run has exactly one true starting point: the value whose predecessor isn't in the set.

HINT 3 ONE STEP FROM THE ANSWER

For each value with no predecessor in the set, walk forward counting how far value+1, value+2, … stay present. Every number gets counted this way only once across the whole array.

COACH'S BOARD — THE PATTERN, STEP BY STEP
RUN STARTS ONLYPATTERN · HASH SET, START POINTS ONLYnums = [100, 4, 200, 1, 3, 2]
100
4
200
1
3
2
VALUE SET
set{100,4,200,1,3,2}
STEP 1

nums = [100, 4, 200, 1, 3, 2]. Drop everything into a set, then walk forward only from true run starts.

STEP 1 / 7 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/longest-consecutive-sequence.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        values = set(nums)
        best = 0
        for x in values:
            if x - 1 not in values:  # only walk forward from a true run start
                length = 1
                while x + length in values:
                    length += 1
                best = max(best, length)
        return best
TIME O(N)SPACE O(N)PYTHON · RACE PACE · 11 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED