Longest Consecutive Sequence
Master this topic with zero to advance depth.
Longest Consecutive Sequence
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
Union-Find Perspective
If nums contains x and x+1, we can Union(x, x+1). The size of the largest component is the answer.
Examples
Input: nums = [100,4,200,1,3,2]
Output: 4
Approach 1
Level I: Sorting + HashSet
Intuition
Sort the array and then iterate through it, checking if the current number is exactly one greater than the previous one. A HashSet can also be used to query neighbors in time and expand sequences.
⏱ O(N log N) for sorting, or O(N) with HashSet.💾 O(N).
Approach 2
Level III: Union-Find (Set Growth)
Intuition
Iterate through each number num. If num+1 exists in the set, union num and num+1. Keep track of the size of each component.
⏱ O(N \cdot \alpha(N)).💾 O(N).
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.