Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. Must run in O(n).
The O(n) constraint rules out sorting. Key insight: only start counting a sequence from its beginning. A number n is the start of a sequence if and only if (n-1) is NOT in the set. This avoids redundant counting — we only count each sequence once, from its true start.
Add all numbers to a set for O(1) lookup.
For each number n, check if (n-1) is in the set. If it IS, skip — we'll count this sequence when we reach its start. If it's NOT, n is a sequence start. Count upward (n+1, n+2...) while in set.
Each number is visited at most twice — once when checking if it's a start, once when counting from a start. Total O(n).
def longestConsecutive(self, nums: List[int]) -> int:
num_set = set(nums)
best = 0
for n in num_set:
if n - 1 not in num_set: # n is a sequence start
length = 1
while n + length in num_set:
length += 1
best = max(best, length)
return bestWhat pattern do you think this problem uses?