Find the length of the longest consecutive elements sequence.
This problem follows the Hash Set Sequence pattern, commonly found in the Arrays & Hashing category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Add all to a set. For each number with no left neighbor, count the sequence length.
Only start counting from sequence beginnings (numbers with no left neighbor) — this ensures each element is visited at most twice, giving O(n).
numSet = set(nums)
longest = 0
for num in numSet:
if num - 1 not in numSet: # start of sequence
length = 1
while num + length in numSet:
length += 1
longest = max(longest, length)
return longestPractice Longest Consecutive Sequence and similar Arrays & Hashing problems with flashcards. Build pattern recognition through active recall.
Practice this problem