Skip to content

Longest Consecutive Sequence

MediumArrays & Hashing
Decode it first. Clues, constraints, pattern and plan before any code.

Given an unsorted list of integers nums, return the length of the longest run of consecutive values (like 4, 5, 6, 7) that can be formed from its elements. The values do not need to be next to each other in the list. Your solution must run in O(n) time.

nums = [100, 4, 200, 1, 3, 2]          →  4   (1, 2, 3, 4)
nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]  →  9   (0 through 8)
nums = []                              →  0

Duplicates may appear and count once.

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9