AAlgoLoopSpaced repetition for LeetCode
MEDIUMHash Map / SetLeetCode ↗

Longest Consecutive Sequence

The key idea

Drop every value into a hash set, then only start counting a run from a value x whose predecessor x - 1 is not in the set. That value is the head of its run, so each run is walked exactly once and the whole scan stays O(n).

Problem

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

A consecutive elements sequence is a run of numbers that follow one another with no gaps, such as [3, 4, 5, 6]. The numbers may appear in any order inside nums, and the run you measure does not have to be contiguous in the array — only the values must be consecutive.

You must write an algorithm that runs in O(n) time.

Constraints

Examples

Input: nums = [100,4,200,1,3,2] Output: 4
Input: nums = [0,3,7,2,5,8,4,6,0,1] Output: 9

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Hash Map / Set problems