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, 2, 3, 4. The run can use values from any positions.
The solution must run in O(n) time, so sorting is not allowed.
Example 1
Input:
[[100,4,200,1,3,2]]
Output:
4
The run 1, 2, 3, 4 has length 4.
Example 2
Input:
[[0,3,7,2,5,8,4,6,0,1]]
Output:
9
0 through 8, with 0 repeated.
Constraints
- 0 ≤ nums.length ≤ 10,000
- -1,000,000 ≤ nums[i] ≤ 1,000,000
- Duplicate values are allowed
Learn the idea first: Hash sets and maps in practice: counting, lookup, deduplication, a visual lesson.
More Hash sets and maps in practice: counting, lookup, deduplication problems
- Contains duplicate Warm-up
- Build a frequency map Warm-up
- Two Sum Standard
- First unique character Standard
- Group anagrams Standard
- Intersection of arrays Standard