Length of the Longest Run of Consecutive Numbers

Implement longestConsecutiveSequence

Given an unsorted array nums, return the length of the longest run of consecutive integers that all appear somewhere in the array. The numbers don't need to be next to each other in the array itself — for [100, 4, 200, 1, 3, 2], the values 1, 2, 3, 4 are each present somewhere, forming a run of length 4. Checking "is the next number present?" by re-scanning the array every time works, but it's wasteful — the same values get searched for again and again from different starting points. Putting every number into a hash setHash SetA collection that answers "is this value present?" in O(1) time on average, instead of scanning through every element. turns each membership check into O(1). The remaining trick is to only start counting from numbers that are genuine sequence starts — where num - 1 is NOT in the set — so every number in the array is ever counted at most once, keeping the whole algorithm at O(n).

Example 1:

Input: nums = [100,4,200,1,3,2]

Output: 4

Example 2:

Input: nums = [0,3,7,2,5,8,4,6,0,1]

Output: 9

Example 3:

Input: nums = [1,2,0,1]

Output: 3

+ 8 hidden test cases run on Submit.

Constraints:

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

nums =

[100, 4, 200, 1, 3, 2]