MemotivaLeetCode Patterns Flashcards: Arrays and Hashing, Frequency Maps, Duplicates

How do you find the longest consecutive sequence in an unsorted array?

LeetCode Patterns Flashcards: Arrays and Hashing, Frequency Maps, Duplicates

Аудио-карточка · 0:31

Nortren·

How do you find the longest consecutive sequence in an unsorted array?

0:31

Insert all elements into a hash set for O of one lookups. For each element, check if it is the start of a sequence by verifying that element minus one is not in the set. If it is a start, count consecutive elements by checking element plus one, plus two, and so on until the chain breaks. Track the maximum length found. This runs in O of n time because each element is visited at most twice: once during the outer loop and once during chain extension. The key insight is only starting chains from sequence beginnings, which prevents redundant work and keeps the total operations linear.
neetcode.io