Skip to content

Longest Consecutive Sequence ​

Longest Consecutive Sequence — LeetCode

Given an unsorted array, find the length of the longest sequence of consecutive integers it contains, in O(n) time.

Approach ​

Need to imagine it on a number line. Convert nums to a hashSet. For each num in hashSet, check if num - 1 exists. If it does, try to check how many consecutive numbers exist by adding 1, and update the counter.

Remarks ​

There is some other version with a HashMap, that stores the number of left and right of a number that seems much better.