All problems

Longest Consecutive Sequence

Medium · hash map

Given an unsorted list of integers nums, return the length of the longest run of consecutive values that appear in it.

A run is a set of values like 4, 5, 6, 7, each exactly one more than the one before. The values can sit anywhere in nums, in any order, so nums = [7, 4, 6, 5] contains the run 4, 5, 6, 7. Duplicates do not extend a run. If nums is empty, return 0.

Examples

Example 1

Input: nums = [100, 4, 200, 1, 3, 2]

Output: 4

The values 1, 2, 3, 4 form a run of length 4. Nothing else comes close.

Example 2

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

Output: 9

The values 0 through 8 are all present. The second 0 is a duplicate and adds nothing.

Example 3

Input: nums = []

Output: 0

Constraints