Arrays & Hashing
LC #128Medium
Longest Consecutive Sequence
Arrays & Hashing
MetaAmazonGoogleBloombergProblem
Given an unsorted integer array, return the length of the longest sequence of consecutive integers (e.g. 4,5,6,7). Must run in O(n) — sorting is O(n log n) and won't count. Example: [100,4,200,1,3,2] → 4 because [1,2,3,4] is the longest consecutive run.
arrayhash-setunion-find
Constraints
- ›0 ≤ nums.length ≤ 10⁵
- ›-10⁹ ≤ nums[i] ≤ 10⁹
- ›O(n) time required
Example
Input
nums = [100, 4, 200, 1, 3, 2]Output
4Why
Consecutive sequence [1, 2, 3, 4] has length 4