Longest Consecutive Sequence

mediumArrays & Hashinghash set + only expand from sequence startsB75Solve on LeetCode#128

Part of Practice: Beyond the Basics

Given an unsorted array of integers, find the length of the longest run of consecutive values — numbers that follow each other like 1, 2, 3, 4 — that can be formed from the array's elements. The elements do not need to be adjacent in the array, and duplicates do not extend a run.

The required time bound is O(n), which rules out sorting first. The array can be empty and can hold up to 100,000 values.

Examples

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

The longest consecutive run is 1, 2, 3, 4 — length 4.

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

The values 0 through 8 are all present (the duplicate 0 adds nothing), giving a run of length 9.

Input:
nums = []
Output:
0

Hints

One at a time — struggle first, peek second.

Your thinking space — verify on LeetCode, then mark it.