Skip to content
mlmentorship

Longest Consecutive Sequence

Find the length of the longest run of consecutive values in an unsorted array.

Published · 22 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Longest Consecutive Sequence

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. An unsorted integer list nums, possibly containing negatives and duplicates. Output. Return the greatest number of distinct values in any run increasing by exactly one each time. Rules. Values need not be adjacent or appear in increasing input order. Repeated copies of a value do not extend a run. Return only the length, not the values or indices. Do not change the input. Empty input returns zero. Example. [100, 4, 200, 1, 3, 2] returns 4 for the run 1, 2, 3, 4. For [1, 1, 2], return 2, because the repeated 1 adds no new consecutive value.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Only values without a predecessor start a run; then advance one value at a time.

Problem trace

Start a walk only where the consecutive run has no predecessor

Worked example: start a run only where no predecessor existsFor set (1,2,3,8), start at 1 and 8. Starting again at 2 or 3 repeats work inside the already-covered run.A value without a predecessor startsa whole maximal run1start238startStarting at one covers 1,2,3 once.Eight begins its separate run.Two and three stay in the set; theirexisting predecessors rule outredundant starts.
Read it this way: For set (1,2,3,8), start at 1 and 8. Starting again at 2 or 3 repeats work inside the already-covered run. Does rejecting two as a new run start remove two from the existing one-to-three run?
Full interview answer 22 min read
Reading depth

Find the longest run of consecutive integer values present anywhere in an unordered input list.

Problem

Input. An unsorted integer list nums, possibly containing negatives and duplicates.

Output. Return the greatest number of distinct values in any run increasing by exactly one each time.

Rules. Values need not be adjacent or appear in increasing input order. Repeated copies of a value do not extend a run. Return only the length, not the values or indices. Do not change the input. Empty input returns zero.

Example. [100, 4, 200, 1, 3, 2] returns 4 for the run 1, 2, 3, 4. For [1, 1, 2], return 2, because the repeated 1 adds no new consecutive value.

Picture: Expand Only a Run’s First Value

Problem trace

Separate full set: walk runs only from predecessor-free starts

Input and goalFind the length of the longest run of consecutive values in an unsorted array.
Build the membership setDeduplicate nums into {1,2,3,4,100,200}; best starts at 0. Sorted display does not change set membership or the answer.
next candidate 11021324310042005
examplenums = [100, 4, 200, 1, 3, 2]; set displayed in sorted ordermapLabelscalar state and membership queryset{1,2,3,4,100,200}
scalar state and membership querybest0
key best
0
next candidate 1
0
example
nums = [100, 4, 200, 1, 3, 2]; set displayed in sorted order

Recognize it
The input is unsorted and asks for consecutive integer values, not consecutive positions, while near-linear time rules out sorting as the intended mechanism.
Keep true
A run is expanded only from its unique smallest value, identified by missing predecessor; best is the maximum completed run length seen so far.
Reuse it
Before expanding a component, find a unique boundary that only one member can satisfy; this avoids duplicate work in runs, intervals, and component scans.
Deduplicate nums into {1,2,3,4,100,200}; best starts at 0. Sorted display does not change set membership or the answer. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does value 2 not start a second walk? Why does that matter for total work?
Reference drawing

Problem trace

Start a walk only where the consecutive run has no predecessor

Worked example: start a run only where no predecessor existsFor set (1,2,3,8), start at 1 and 8. Starting again at 2 or 3 repeats work inside the already-covered run.A value without a predecessor startsa whole maximal run1start238startStarting at one covers 1,2,3 once.Eight begins its separate run.Two and three stay in the set; theirexisting predecessors rule outredundant starts.
Execution trace
Input and goalFind the length of the longest run of consecutive values in an unsorted array.
Build the membership setDeduplicate nums into {1,2,3,4,100,200}; best starts at 0. Sorted display does not change set membership or the answer.
next candidate 11021324310042005
examplenums = [100, 4, 200, 1, 3, 2]; set displayed in sorted ordermapLabelscalar state and membership queryset{1,2,3,4,100,200}
scalar state and membership querybest0
key best
0
next candidate 1
0
example
nums = [100, 4, 200, 1, 3, 2]; set displayed in sorted order

Recognize it
The input is unsorted and asks for consecutive integer values, not consecutive positions, while near-linear time rules out sorting as the intended mechanism.
Keep true
A run is expanded only from its unique smallest value, identified by missing predecessor; best is the maximum completed run length seen so far.
Reuse it
Before expanding a component, find a unique boundary that only one member can satisfy; this avoids duplicate work in runs, intervals, and component scans.
Deduplicate nums into {1,2,3,4,100,200}; best starts at 0. Sorted display does not change set membership or the answer. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does value 2 not start a second walk? Why does that matter for total work?
Read it this way: For set (1,2,3,8), start at 1 and 8. Starting again at 2 or 3 repeats work inside the already-covered run. Does rejecting two as a new run start remove two from the existing one-to-three run?

The sorted set display is not input order or execution order. Small cell indices locate displayed values only.

CandidatePredecessorAction
10 absentAdvance through 2, 3, 4; missing 5 ends length 4
2, 3, 4PresentSkip these interior starts
10099 absentSingleton; best stays 4
200199 absentSingleton; best stays 4

Each distinct value gets one predecessor test. Each belongs to one expanded run; successful successor steps total . Here counts distinct values and counts maximal runs. Each run also ends with one failed successor query. Thus all successor queries total , not , regardless of set iteration order.

Code

def longest_consecutive(nums: list[int]) -> int:
   values = set(nums)
   best = 0

   for start in values:
      if start - 1 in values:
         continue

      end = start
      while end + 1 in values:
         end += 1
      best = max(best, end - start + 1)

   return best

Expected time is , including set construction; space is , with . This assumes expected constant-time hashing and ordinary integer arithmetic.

Change 1: Return a Deterministic Witness

New task. Return run values, choosing the smallest start on ties.

Picture and change. Save length and start; materialize only the winner.

Code.

def longest_run_values(nums):
   values = set(nums)
   best_start, best_length = None, 0
   for start in values:
      if start - 1 in values:
         continue
      end = start
      while end + 1 in values:
         end += 1
      length = end - start + 1
      if length > best_length or (length == best_length and start < best_start):
         best_start, best_length = start, length
   return [] if best_start is None else list(range(best_start, best_start + best_length))

Check. [8, 9, 1, 2] returns [1, 2]; empty input returns [].

Use when. A reproducible witness matters. Its output storage is additional.

Change 2: A Fixed Positive Integer Step

New task. Consecutive members differ by step, not necessarily 1.

Picture and change. Test start-step, advance end+step, and measure length in steps.

Code.

def longest_fixed_step(nums, step):
   if step <= 0:
      raise ValueError("positive step required")
   values = set(nums)
   best = 0
   for start in values:
      if start - step in values:
         continue
      end = start
      while end + step in values:
         end += step
      best = max(best, (end - start) // step + 1)
   return best

Check. [1, 3, 5, 2, 4], step 2, gives 3; [-3, -1, 1] also gives 3. Step zero raises an error instead of invalidating progress.

Use when. A fixed successor spacing still partitions values into disjoint runs.

Failure: Starting From Every Member

Expanding suffixes from every value of a length- run costs work, which is quadratic.

Transfer Check

Why do the nested loops not make the reference quadratic?

Reasoned Answer

Only the unique start expands each disjoint run. Charge each successful advance to a distinct value, not every outer iteration.

What Information Does the Set Discard?

It forgets input order and multiplicity, neither of which changes this length-only answer. An adjacent-position requirement would be different: [1, 3, 2] contains value run 1, 2, 3, not an adjacent increasing run. That task needs positional information the set discarded.

The outer loop must use distinct values too. Repeating a run’s head from the original duplicated input can rescan the same run. The predecessor guard alone does not prevent those repeated-head scans.

The witness tie rule is needed only because the output now selects particular values. The reference’s maximum length does not depend on iteration order. Fixed positive spacing preserves one predecessor and successor per integer, but a general graph can branch or cycle. Do not transfer this start-only proof to arbitrary connected components without traversal and visited-state reasoning.