Longest Consecutive Sequence
Difficulty: Medium
Problem
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
Example
Input: nums = [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive sequence is [1, 2, 3, 4]. Its length is 4.
Brute-force approach
Sort the array and find longest consecutive run.
Steps
- Sort the array
- Iterate and count consecutive elements
- Handle duplicates
- Track maximum streak
Time complexity: O(n log n) · Space complexity: O(1) or O(n)
Trade-offs
- Sorting takes O(n log n)
- Modifies array (or needs copy)
- Can we avoid sorting?
Optimal approach
Key insight: A number is a sequence START only if (num - 1) is NOT present in the set!
Use a Set for O(1) lookup. Only start counting from sequence beginnings (no predecessor).
Steps
- Put all numbers into a HashSet
- Loop through numbers
- If (num-1) not in set → it's a sequence start
- Count consecutive numbers from that start
- Track the longest streak
Time complexity: O(n) · Space complexity: O(n)