Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example: For nums = [100, 4, 200, 1, 3, 2], the longest consecutive sequence is [1, 2, 3, 4], with length 4.
Union Find Approach:
Key Insight: Consecutive numbers should belong to the same set. By unioning n with n+1 when both exist, we build sets of consecutive sequences.
Note: This problem can also be solved with HashSet approach, but Union Find demonstrates how to think about "grouping related elements."
nums = [100,4,200,1,3,2]4nums = [0,3,7,2,5,8,4,6,0,1]9nums = []0nums = [1]10 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9Click "Run" to execute your code against test cases
Socratic guidance - I'll ask questions, not give answers