noodleProblems/
Longest Consecutive Sequence
#107

Longest Consecutive Sequence

AlgorithmmediumArrayHash Table

Given an unsorted array of integers nums, return the length of the longest run of consecutive integers — values that differ by exactly 1 from their neighbour in the run.

The numbers do **not** have to be adjacent (or in order) inside nums; only their *values* must be consecutive. Duplicate values count once.

Aim for an O(n) algorithm — fast enough that you never need to sort the input.

Example cases

  • basic
    in nums = [100,4,200,1,3,2]
    out 4
    The run [1, 2, 3, 4] has length 4. 100 and 200 are isolated.
  • longer run with a duplicate
    in nums = [0,3,7,2,5,8,4,6,0,1]
    out 9
    0 through 8 are all present (0 appears twice but counts once), so the run [0..8] has length 9.
  • empty
    in nums = []
    out 0
    No numbers means no run.

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Saved
nums =
[100,4,200,1,3,2]