Longest Consecutive Sequence
Find the longest run of consecutive integers in an unsorted array in O(n), using a hash set.
The problem
You get an unsorted integer array nums. Return the length of the longest sequence of consecutive whole numbers, like 4, 5, 6, 7, whose values all appear in nums; they can sit anywhere in the array, and repeated values count once. Your solution should run in O(n) time.
Input nums = [9, 1, 4, 7, 3, 2, 8]
Output 4
1, 2, 3, 4 is the longest run; 7, 8, 9 has only three numbers.
Input nums = [2, 0, 1, 1, -5]
Output 3
The two 1s count once, so the run 0, 1, 2 has length 3.
Key constraint: The time limit is O(n), so sorting, which takes O(n log n), is not the intended solution.
How to spot the pattern
- Only which values are present matters, not where they sit in the array.
- You keep asking "is x + 1 there?", which a hash set answers in O(1).
- The O(n) requirement rules out sorting.
The idea
Put every value in a hash set so you can ask "is this number present?" in O(1). A number x starts a run only when x - 1 is missing; from each start, count upward while x + 1, x + 2 and so on are in the set. Every number is stepped over by at most one of these upward walks, so the total work stays O(n) even though there is a loop inside a loop.
Brute force: Sort the numbers and count runs of neighbours that differ by 1, which works but takes O(n log n) time.
Step by step
- 1Put all the numbers into a hash set, which also drops the duplicates.
- 2For each number
xin the set, skip it ifx - 1is also in the set, because thenxis not the start of a run. - 3From a start, count how many of
x + 1,x + 2, ... are in the set, stopping at the first gap. - 4Keep the longest run length you find, and return it (0 for an empty array).
See the pattern move
The hashing pattern on a small example. Step through it, or press play.
Code
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
values = set(nums)
best = 0
for x in values:
if x - 1 in values:
continue # x is not the start of a run
length = 1
while x + length in values:
length += 1
best = max(best, length)
return bestComplexity
Time
O(n)
Space
O(n)
The inner loop only runs from the start of a run, so across the whole outer loop each number is stepped over at most once; the set holds up to n numbers.
Watch out for
- Starting an upward walk from every number instead of only from run starts, which is O(n^2) on an input like 1, 2, 3, ..., n.
- Looping over the original array instead of the set: if the start of a long run appears thousands of times, the same long walk repeats for every copy.
- Counting repeated values as part of the run: [1, 2, 2, 3] has a run of length 3, not 4.
Follow-up questions
What if the numbers arrive one at a time and you need the answer after each one?
Keep a map from the two ends of each run to its length. When a new x arrives, look up the run ending at x - 1 and the run starting at x + 1, join them through x, and update only the two outer ends. Each arrival costs O(1).
When is sorting the better answer?
When O(n log n) is acceptable and memory is tight: sorting in place needs no hash set, and the scan for runs is short. Say this trade-off out loud before writing the set version.
In Hinglish
Sab numbers set mein daalo. Jis number ka x - 1 set mein nahi hai, wahi run ka start hai; wahan se aage ginte jao.