Longest Consecutive Sequence
Problem Statement
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.
Constraints:
- 0 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
Input Format:
- An unsorted array of integers nums
Output Format:
- The length of the longest consecutive elements sequence
Examples:
Example 1:
Input:
nums = [100,4,200,1,3,2]
Output:
4
Explanation:
The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore 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]. Therefore its length is 9.
Example 3:
Input:
nums = []
Output:
0
Explanation:
The array is empty, so the length of the longest consecutive sequence is 0.
Solutions
Hash Set Approach
Use a hash set to efficiently check for the presence of consecutive elements.
Union Find Approach
Use a Union Find data structure to group consecutive elements and keep track of the size of each group.
Sorting Approach
Sort the array first, then count consecutive elements. This approach is simpler but does not meet the O(n) time requirement.
Algorithm Walkthrough
Example input: nums = [100,4,200,1,3,2]
Step-by-step execution:
- Create a set: {1, 2, 3, 4, 100, 200}
- Iterate through the set:
- Check 1: 1-1=0 is not in the set, so 1 is the start of a sequence
- Count consecutive numbers: 1, 2, 3, 4 (length = 4)
- Check 2: 2-1=1 is in the set, not the start of a sequence, skip
- Check 3: 3-1=2 is in the set, not the start of a sequence, skip
- Check 4: 4-1=3 is in the set, not the start of a sequence, skip
- Check 100: 100-1=99 is not in the set, so 100 is the start of a sequence
- Count consecutive numbers: 100 (length = 1)
- Check 200: 200-1=199 is not in the set, so 200 is the start of a sequence
- Count consecutive numbers: 200 (length = 1)
- Max sequence length = 4
Hints
Hint 1
Hint 2
Hint 3
Video Tutorial
Video tutorials can be a great way to understand algorithms visually
Visualization
Visualize the consecutive sequences found in the array.
Key visualization elements:
- current number
- current sequence
- longest sequence
Implementation Notes
This problem has a clever O(n) solution that uses a hash set to avoid sorting while still efficiently determining the longest consecutive sequence.