Longest Consecutive Sequence

MediumArrays and hashing

The values in nums are in no order. Find the longest run of consecutive integers, such as 4, 5, 6, 7, whose every value is somewhere in nums, and return its length.

Aim for O(n) time.

Examples

Example 1
Input:  nums = [9, 1, 7, 3, 8, 2, 30, 10]
Output: 4

7, 8, 9 and 10 are all present. 1, 2, 3 is a shorter run, and 30 stands alone.

Example 2
Input:  nums = [5, 5, 6, 6]
Output: 2

Repeats do not make a run longer: 5, 6 is two long.

Constraints

  • 0 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹

Stuck?

Hint 1

Put every value in a Set. A run can only start at a value whose predecessor, value - 1, is missing.

Hint 2

From each such start, count upward while the next value is in the Set. Each value is then counted once, so the whole thing is O(n).

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur