PracticeNeetCode ↗LeetCode ↗
Given an unsorted array of integers nums, return the length of the longest run of consecutive integers it contains — in O(n) time (no sorting).
num - 1 is not in the set.n in the set, check if n - 1 is also in the set — if it is, skip (n isn't a run's start).n is a start, count forward: while n + length is in the set, increment length.Time: O(n) — Space: O(n)
def longestConsecutive(nums: list[int]) -> int:
num_set = set(nums)
longest = 0
for n in num_set:
if n - 1 not in num_set:
length = 1
while n + length in num_set:
length += 1
longest = max(longest, length)
return longestHow the solution above works, piece by piece.
num_set = set(nums): O(1) membership checks, and duplicates disappear.if n - 1 not in num_set: only begin counting at the start of a run. For 2, 3, 4 this is false, so they are skipped.while n + length in num_set: length += 1: walk right from the start as long as the next number exists.longest = max(longest, length) keeps the best run.while loop at most once (only from its own run's start), so O(n) total instead of O(n log n) for sorting.Running it on nums = [100, 4, 200, 1, 3, 2]:
n − 1 missing) start counting. So each run is walked once, from its start, and the whole thing stays O(n) even though there is a loop inside a loop.