8. Longest Consecutive Sequence

Return the length of the longest run of consecutive integers (like 4, 5, 6, 7) that can be formed from the values in nums. The values do not need to be adjacent in the array. Aim for O(n).

Example 1

Input: nums = [10,4,20,1,3,2]
Output: 4
Explanation: The run is 1, 2, 3, 4.

Example 2

Input: nums = [9,1,-1,8,0,10,2]
Output: 4
Explanation: The run is -1, 0, 1, 2.

Constraints

  • 0 ≤ nums.length ≤ 10⁵
Hint 1

Put everything in a set.

Hint 2

Only start counting from numbers that have no left neighbour (x − 1 is missing).

Hash TableUnion Find