Problem 5 · Arrays & Hashing
Longest Consecutive Sequence
01Problem
Given an unsorted integer array, return the length of the longest run of consecutive integers, in O(n) time.
02Key insight
Put everything in a set and only start counting from run starts (x-1 not in set), so each element is visited a constant number of times overall.
03Solution
Try it first.
TimeO(n)
SpaceO(n)
tests.py · 3 passing
tests.pypython3 lines
assert longest_consecutive([100,4,200,1,3,2]) == 4
assert longest_consecutive([0,3,7,2,5,8,4,6,0,1]) == 9
assert longest_consecutive([]) == 004Staff-level follow-up
What if numbers arrive as a stream? Use union-find (or a map of run boundaries) to merge x with x-1 and x+1 on insert, tracking max component size in near-O(1) amortised.