Longest consecutive sequence
Challenge · Write code · about 18 min
Given an unsorted integer array nums, return the length of the longest run of consecutive integers, such as -1, 0, 1, 2. The values of a run can sit at any positions.
Solve it in O(n) time, so sorting is not allowed.
Example 1
Input:
[[9,1,-1,8,0,2,10]]
Output:
4
The run -1, 0, 1, 2 has length 4. The run 8, 9, 10 has length 3.
Example 2
Input:
[[5,6,100,7,101,8]]
Output:
4
5, 6, 7, 8.
Constraints
- 0 ≤ nums.length ≤ 10,000
- -1,000,000 ≤ nums[i] ≤ 1,000,000
- Values may repeat
Learn the idea first: Hash maps for lookup and counting, a visual lesson.
More Hash maps for lookup and counting problems
- Contains duplicate Warm-up
- Fill the seen-set Warm-up
- Isomorphic strings Standard
- Subarray sums divisible by k Standard