Find the length of the longest run of integers that appear consecutively in an unsorted array.
Given an unsorted array of integers, return the length of the longest sequence of numbers that can be arranged into a consecutive run.
A consecutive run means each next value is exactly 1 larger than the previous value, and the values do not need to appear next to each other in the input array. Duplicate values may appear in the input, but they should not increase the length of a run.
Your task is to compute only the maximum length of such a run.
Input Format
- An integer array
nums. numsmay contain positive, negative, and duplicate integers.
Output Format
- Return a single integer: the length of the longest consecutive sequence present in
nums.
Constraints
- The array may be empty.
- Duplicate values should be ignored for sequence length purposes.
- Aim for better than quadratic time.
Example 1
Input
nums = [100, 4, 200, 1, 3, 2]
Output
4
Explanation
The longest consecutive run is [1, 2, 3, 4], which has length 4.
Example 2
Input
nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Output
9
Explanation
The run [0, 1, 2, 3, 4, 5, 6, 7, 8] has length 9. The duplicate 0 does not change the answer.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.