Length of the Longest Run of Consecutive Integers
Arrays & HashingAuto-graded · 24 test casesLast updated
Tests whether a candidate can find the longest chain of consecutive integers in an unsorted array in linear time using a hash set.
Longest Chain of Consecutive Values
You are given an unsorted array of integers. Your task is to find the length of the longest chain of consecutive integers that all appear somewhere in the array — regardless of where they sit in it.
For example, if the array contains the values 1, 2, 3, and 4 scattered across various positions, that chain has length 4.
Rules
- Order does not matter. Only the values count, not their positions in the array.
- Duplicates count once. If the same value appears more than once it contributes a single slot to any chain it belongs to.
- Negative numbers and zero are valid inputs.
- Return
0for an empty array. - Your solution must run in O(n) time.
Constraints
0 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9- Element values may repeat.
- You may not assume the array is sorted.
Examples
Example 1
Input: longest_consecutive_chain([100, 4, 200, 1, 3, 2])
Output: 4
Example 2
Input: longest_consecutive_chain([0, 3, 7, 2, 5, 8, 4, 6, 0, 1])
Output: 9
Hints
Hint 1
Load all values into a hash set first. Membership checks become O(1), and duplicates disappear automatically.
Hint 2
A chain has exactly one starting point — the smallest value in it. A value starts a chain only when the integer just below it is absent from the set. Use that fact to avoid re-walking the same chain from every element inside it.
Hint 3
Once you find a chain start, keep stepping one integer upward and count how far you can go before hitting a value that is missing from the set. Track the longest count seen across all chain starts.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight
The brute-force approach — for every element, walk upward counting how far the chain extends — is O(n²) because it re-walks the same chain from every element inside it. The fix is to only ever start walking from the bottom of a chain.
A value v is the bottom of a chain when v - 1 is not in the collection. That check costs O(1) with a hash set, and it ensures each chain is walked exactly once, from its smallest element upward.
Step-by-step
- Copy all values into a hash set. This gives O(1) membership queries and eliminates duplicates.
- Iterate over every distinct value in the set.
- Skip the value if
value - 1is also in the set — it is not a chain start. - For a confirmed chain start, count upward (
value + 1,value + 2, …) while each next integer exists in the set. - Update the running maximum and continue.
- Return the maximum after all values have been examined.
Why it is correct
Every maximal chain a, a+1, …, a+k-1 has a unique smallest element a. Because the chain is maximal, a - 1 cannot be in the set, so a always passes the start check. The while loop then walks the full chain and records length k. No chain is missed, no chain is walked more than once.
Iterating over the set rather than the original list is important when the same chain-start value appears many times in the input. Without it, a heavily duplicated value would trigger repeated walks of the same chain.
Complexity
Time: O(n) Building the set is O(n). The outer loop visits each distinct value once (O(1) check each time). The inner while loop advances through each value at most once in total across all iterations, because every value belongs to exactly one maximal chain and that chain is walked exactly once. Total work is proportional to the number of distinct elements.
Space: O(n) for the hash set.
Comparison with sorting: sorting the array and scanning for consecutive runs is O(n log n) time but can be done with O(1) extra space. It is a fine baseline answer; the hash-set version is the optimal-time solution.
Edge cases
| Input | Output | Reason |
|---|---|---|
[] | 0 | Loop never runs; longest stays 0 |
[7] | 1 | Single element is its own chain |
[1, 2, 2, 3] | 3 | Duplicate collapses in the set |
[-2, -1, 0, 1] | 4 | Negatives work fine |
[10, 30, 20] | 1 | No two values are adjacent |
[5, 4, 3, 2, 1] | 5 | Input order is irrelevant |
Reference solution
from typing import List
def longest_consecutive_chain(nums: List[int]) -> int:
values = set(nums) # O(1) lookups; duplicates collapse automatically
longest = 0
for value in values:
# Only begin counting at the bottom of a chain
if value - 1 not in values:
length = 1
while value + length in values:
length += 1
longest = max(longest, length)
return longest