Find the longest run of consecutive numbers in an unsorted list. Put them in a set, and only count up from numbers with no left neighbour.
▼The problem
LeetCode 128 (Medium). Given an unsorted array of integers, return the length of the longest run of consecutive values, in O(n) time.
Example (LeetCode's first): [100, 4, 200, 1, 3, 2] → 4 (1, 2, 3, 4; 100 and 200 are runs of one).
The solution
def longestConsecutive(nums):
seen = set(nums)
best = 0
for x in seen:
if x - 1 not in seen: # first domino
y = x
while y + 1 in seen: # push the next
y += 1
best = max(best, y - x + 1)
return bestTranscript
Longest Consecutive Sequence. You get an unsorted array of integers. Return the length of the longest run of consecutive values, like five, six, seven, a run of three. And do it in linear time.
Take one hundred, four, two hundred, one, three and two. One, two, three and four make a run of four. One hundred and two hundred stand alone, runs of one. So the answer is four.
The obvious way sorts the numbers, then scans for runs. That works, but sorting costs order n log n time, not linear.
So skip the sort. Put every number in a hash set instead. Asking whether a value is there now takes constant time.
Think of each run as a row of dominoes. Counting up from every number would recount the same run again and again. Instead, only push the first domino: a number with no number just below it. Four has a three below it, so it's not a start. One has no zero, so it is. From there, keep asking for the next number up until one is missing.
In code, build the set and loop over it. If x minus one is not in the set, x starts a run. Walk y upward while y plus one is present, then keep the longest length.
Let's run it. One hundred has no ninety nine, so it starts a run, but one hundred and one is missing: length one. Four has a three, so skip it. Two hundred is another run of one. One has no zero, so it starts, and pushes two, three and four. Five is missing: a run of four. Three and two are skipped. The best is four.
Why is this linear? Each number is checked once as a possible start, and walked over at most once, inside its own run. That's at most two visits per number, so the time is order n, and the set takes order n space.
Hash it, start only at the bottom of each run, then walk up. That's Longest Consecutive Sequence.