Longest Consecutive Sequence
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given an unsorted array of integers nums, return the length of the longest run of consecutive values that can be formed from its elements.
Your algorithm must run in O(n) time.
Understand the problem
- Consecutive values are whole numbers that follow each other with no gaps:
1, 2, 3, 4is a run of length 4.1, 2, 4is not one run, because3is missing. - The values don't need to be next to each other in the array, and the array isn't sorted. You're allowed to pick values from anywhere.
- A duplicate value counts only once:
[1, 2, 2, 3]has a run of length 3 (1, 2, 3), not 4. - O(n) means you can't sort the array first, because sorting takes O(n log n).
Example 1
Input: nums = [100, 4, 200, 1, 3, 2]
Output: 4The values 1, 2, 3, 4 are all in the array (scattered around), forming a run of 4. 100 and 200 are runs of length 1.
Example 2
Input: nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Output: 9Every value from 0 to 8 is present, a run of 9. The second 0 doesn't add anything.
Example 3
Input: nums = []
Output: 0Constraints
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Put all values in a set, find the values that start a run (their left neighbour is missing), and count upward from each start.
The naive approach (and why it's slow)
- Sort, then scan: after sorting, a run is just neighbours that differ by 1. Simple and correct, but sorting is O(n log n), and the problem demands O(n).
- Count from every value: for each
x, checkx + 1,x + 2, ... by scanning the array. Each check is a full scan, so this gets close to O(n³) in the worst case.
The key insight
Two ideas, one on top of the other:
- Make lookups instant. Put every value in a hash set, so "is
x + 1here?" takes one step. - Only count each run once. Counting from every value repeats work: the run
1, 2, 3, 4would be walked from1, then from2, then from3... Instead, only start counting at the first value of a run. How do we knowxis first? Becausex - 1is not in the set.
Step by step
nums = [100, 4, 200, 1, 3, 2] → set = {100, 4, 200, 1, 3, 2}
| Value | value - 1 in set? | Start of a run? | Walk upward | Length | Longest so far |
|---|---|---|---|---|---|
100 | 99: no | Yes | 100 (no 101) | 1 | 1 |
4 | 3: yes | No, skip | 1 | ||
200 | 199: no | Yes | 200 (no 201) | 1 | 1 |
1 | 0: no | Yes | 1, 2, 3, 4 (no 5) | 4 | 4 |
3 | 2: yes | No, skip | 4 | ||
2 | 1: yes | No, skip | 4 |
Answer: 4.
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n). This surprises people, because there's a loop (
while) inside a loop (for). But the inner walk only runs from starts, and each value belongs to exactly one run. So across the whole algorithm, each value is walked over at most once. Total work: about2nsteps, which is O(n). - Memory: O(n) for the set.
Common mistakes
- Skipping the "is it a start?" check. The code still gives the right answer, but a long run gets walked again from every one of its values, which is O(n²).
- Looping over the array instead of the set. With many copies of a start value (like
[1, 1, 1, ..., 2, 3]), you'd repeat the same walk once per copy. Looping over the set visits each distinct value once. - Forgetting the empty array. With no values, the answer is
0, and your loop should simply never run.
Going deeper
The "only act at the start of a group" trick is useful far beyond this problem: whenever nested loops make a solution look O(n²), ask whether each item is really processed more than once in total. If not, it's O(n). This kind of reasoning is called amortized analysis.
Reference solution
/**
* @param {number[]} nums
* @return {number}
*/
export default function longestConsecutive(nums) {
// A set makes "is x here?" one step, and drops duplicates for free.
const values = new Set(nums)
let longest = 0
// Loop over the SET, not the array, so each distinct value is visited once.
for (const value of values) {
// value - 1 exists, so value is in the middle of a run. Its run gets counted from its start.
if (values.has(value - 1)) continue
// value is the start of a run: count upward while the next value exists.
let length = 1
while (values.has(value + length)) length++
longest = Math.max(longest, length)
}
return longest
}export default function longestConsecutive(nums: number[]): number {
// A set makes "is x here?" one step, and drops duplicates for free.
const values = new Set(nums)
let longest = 0
// Loop over the SET, not the array, so each distinct value is visited once.
for (const value of values) {
// value - 1 exists, so value is in the middle of a run. Its run gets counted from its start.
if (values.has(value - 1)) continue
// value is the start of a run: count upward while the next value exists.
let length = 1
while (values.has(value + length)) length++
longest = Math.max(longest, length)
}
return longest
}def longest_consecutive(nums: list[int]) -> int:
# A set makes "is x here?" one step, and drops duplicates for free.
values = set(nums)
longest = 0
# Loop over the SET, not the list, so each distinct value is visited once.
for value in values:
# value - 1 exists, so value is in the middle of a run. Its run gets counted from its start.
if value - 1 in values:
continue
# value is the start of a run: count upward while the next value exists.
length = 1
while value + length in values:
length += 1
longest = max(longest, length)
return longest