Practice

Longest Consecutive Sequence

Module 6 · Hash Tables

Problem

Given an unsorted array nums, return the length of the longest run of consecutive integer values (positions in the array don't matter). You must run in O(n).

Examples

Example 1

Inputnums = [100,4,200,1,3,2]Output4

Explanation. 1,2,3,4

Example 2

Inputnums = [0,3,7,2,5,8,4,6,0,1]Output9

Explanation. 0..8

Example 3

Inputnums = []Output0

Constraints

0 ≤ n ≤ 10⁵ · values in ±10⁹ · O(n) required.

Attempt it first

This is the module capstone: the required O(n) is the entire puzzle. The obvious good solution — sort, scan for runs — is O(n log n), and the problem explicitly bans it. Sit with it for a while; the trick is a new kind of move, and meeting it cold is worth real struggle.