Practice · Hashing · 6 of 7

Longest Run of Consecutive Values

You are given an unsorted list of integers nums. Return the length of the longest run of consecutive integers (such as 4, 5, 6, 7) whose values all appear somewhere in nums. The values can sit at any positions, and a value that appears more than once counts once.

Aim for O(n) time, which rules out sorting.

Example 1

Input
nums = [10, 4, 20, 1, 3, 2]
Output
4
1, 2, 3 and 4 are all in the list.

Example 2

Input
nums = [5, 6, 6, 100, 7, -1, 0]
Output
3
The run 5, 6, 7 is the longest; the repeated 6 counts once.

Constraints

  • nums holds 0 to 10⁵ numbers.
  • Every number is between −10⁹ and 10⁹.
Brush up firstHash Set visualiser