Example 1
- Input
- nums = [100, 4, 200, 1, 3, 2]
- Output
- 4
The longest consecutive run is [1, 2, 3, 4], which has length 4.
Given an unsorted array of integers, return the length of the longest run of consecutive integers it contains. The order in the array does not matter and the algorithm must run in linear time.
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in time. Sorting would place consecutive values side by side, a hash set instead supports expected constant-time membership checks without sorting.
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9The longest consecutive run is [1, 2, 3, 4], which has length 4.
The longest consecutive run is [0, 1, 2, 3, 4, 5, 6, 7, 8], which has length 9.
The distinct values 0, 1, and 2 form one run of length 3. The second occurrence of 1 adds no new consecutive value.
No integers means there is no run to count.
Consecutive values differ by one; their positions in the array do not matter. In [100, 4, 200, 1, 3, 2], the values 1 through 4 form a run even though they are scattered. Store values in a set for quick membership checks. Start counting only where the previous integer is missing: 1 starts the run, while 2, 3, and 4 do not.
Reveal Sorting: intuition, complexity, and code
10^5 elements.num - 1 is missing, so each run is counted exactly once.0.[1, 2, 0, 1] must not inflate the run; the set collapses them and the sort skips equal neighbors.For consecutiveness questions, store values in a hash set and anchor each piece of work at a start condition so no element is processed twice.