1Question
You are given an array of numbers nums that is not sorted. Find the length of the longest run of consecutive numbers (like 1, 2, 3, 4) that you can build from its values.
The numbers in the run do not need to be next to each other in the array. Only the values matter. Your algorithm must run in O(n) time.
The run is 1, 2, 3, 4. It has length 4.
The run is 0, 1, 2, 3, 4, 5, 6, 7, 8. The extra 0 does not count twice.
The run is 0, 1, 2. The duplicate 1 is counted only once.
Constraints
Up to 100,000 numbers. The array can also be empty, and then the answer is 0.
Values can be negative and very large, so we use a hash set, not an array of flags.
You must write an algorithm that runs in O(n) time. Sorting alone costs O(n log n), so we need a smarter idea.
2Hints
Open one hint at a time. Try to think before you open the next one.
3Pattern
Hash Set Sequence Starts
Put everything in a set, then only walk a run from its first number.
A set answers “does this value exist?” in O(1). If we also know where each run begins, we can count every run exactly once, with no sorting:
Every run has exactly one start. Numbers in the middle of a run are skipped, so no number is walked over again and again.
How to spot this pattern
- The question is about values that follow each other (1, 2, 3, ...) in an unsorted array.
- The order in the array does not matter, only which values exist.
- The problem asks for O(n), which rules out sorting.
- You are allowed O(n) extra memory for a set.
4Explanation
The big idea: Put all numbers in a set called num_set. Then for each number num, ask one question first:
Yes: num is in the middle of a run. Skip it. Someone earlier will count this run.
Then num is the start of a run. Count num + 1, num + 2, ... while they are in the set.
Why is it O(n) and not O(n²)? Each run is walked only from its start. A number inside a run is checked once (and skipped), and then walked over once by the start of its run. So every number is touched a small, fixed number of times.
What about duplicates? A set keeps each value only once, so a repeated number can never make a run longer.
5Brute Force
Sort the values, then count each run of +1 steps.
Idea
After sorting, numbers of the same run sit next to each other. So we:
- Remove duplicates and sort the values.
- Walk through the list. If the number is
previous + 1, the run grows by 1. - Otherwise the run is broken, so start a new run with length 1.
- Remember the longest run you saw.
def longest_consecutive_brute(nums):
if not nums:
return 0
values = sorted(set(nums)) # no duplicates, in order
best = 1
run = 1
for i in range(1, len(values)):
if values[i] == values[i - 1] + 1:
run += 1 # same run keeps growing
else:
run = 1 # gap found, start a new run
best = max(best, run)
return best
print(longest_consecutive_brute([100, 4, 200, 1, 3, 2])) # 46Optimal Solution
A hash set, counting only from the start of each run.
def longest_consecutive(nums):
num_set = set(nums) # O(1) lookups, no duplicates
best = 0
for num in num_set:
if num - 1 not in num_set: # num is the START of a run
length = 1
while num + length in num_set:
length += 1 # walk up the run
best = max(best, length)
return best
print(longest_consecutive([100, 4, 200, 1, 3, 2])) # 47Time and Space Complexity
Let n be the number of items in the array.
Brute force (sort and scan)
Optimal (hash set, walk from starts)
How big is the difference?
Approximate number of steps:
| n | Sort (n log n) | Hash set (n) |
|---|---|---|
| 10 | about 33 | 10 |
| 1,000 | about 10,000 | 1,000 |
| 100,000 | about 1.7 million | 100,000 |
For the biggest input in this problem, the hash set does around 17 times less work than sorting, and it is the only one that meets the O(n) rule.