Longest Consecutive Sequence

Medium
Union Find

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:

  1. Create a set of all numbers for O(1) lookup
  2. For each number n, if n+1 exists in the set, union(n, n+1)
  3. Track the size of each set during union operations
  4. The answer is the maximum set size

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."

Example 1

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Its length is 4.

Example 2

Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
Explanation: The longest consecutive elements sequence is [0, 1, 2, 3, 4, 5, 6, 7, 8]. Its length is 9.

Example 3

Input: nums = []
Output: 0
Explanation: Empty array has no consecutive sequence.

Example 4

Input: nums = [1]
Output: 1
Explanation: Single element forms a sequence of length 1.

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Show Hints (4)
Hint 1: Two numbers are "related" if they are consecutive. How would you model this relationship with Union Find?
Hint 2: For a number n, which other numbers should be in the same set as n?
Hint 3: You need O(n) time. How can you avoid checking all pairs of numbers? (Hint: use a set for O(1) existence checks)
Hint 4: When you union two sets, how do you track the size of the resulting set? (Hint: store size at the root)
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?