Longest Consecutive Sequence
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Union Find.
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).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.