Longest Consecutive Sequence
Master this topic with zero to advance depth.
Longest Consecutive Sequence
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in time.
Visual Representation
nums = [100, 4, 200, 1, 3, 2]
Step 1: Put all in HashSet: {100, 4, 200, 1, 3, 2}
Step 2: Check each number if it's a START (num-1 not in set):
- 100: (99? No) -> Start! Count 101, 102... (Len: 1)
- 4: (3? Yes) -> Not a start.
- 200: (199? No) -> Start! Count 201... (Len: 1)
- 1: (0? No) -> Start! Count 2, 3, 4 (Len: 4) -> MAX!Examples
The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
The longest consecutive elements sequence is [0,1,2,3,4,5,6,7,8].
Level I: Brute Force (Check Each Number)
Intuition
For every number x in the array, we check if it is the start of a sequence by trying to find x+1, x+2, etc., using a linear scan through the array for each step. This leads to a cubic time complexity.
Detailed Dry Run
| Num | Sequence | Max Length |
|---|---|---|
| 100 | [100] (101 not found) | 1 |
| 4 | [4] (5 not found) | 1 |
| 1 | [1, 2, 3, 4] | 4 |
Level II: Better Solution (Sorting)
Intuition
By sorting the array, consecutive numbers are placed adjacent to each other. We can then find sequences by comparing each element with its predecessor. We must handle duplicate elements by skipping them during the streak calculation.
Detailed Dry Run
| Sorted Array | Comparison | Action | Streak |
|---|---|---|---|
| [1, 2, 3, 4, 100, 200] | 2 == 1+1 | Increment | 2 |
| [1, 2, 3, 4, 100, 200] | 100 != 4+1 | Reset | 1 |
Level III: Optimal Solution (HashSet)
Intuition
To achieve linear time, we use a Hash Set for lookups. The key insight is identifying the start of a sequence: a number x is the start if x-1 does not exist in the set. Only then we explore the sequence using a while loop, ensuring each element is visited at most twice.
Detailed Dry Run
Start-of-Sequence Logic
| Number | x-1 In Set? | Action | Streak |
|---|---|---|---|
| 100 | 99 (No) | Start Streak | 1 |
| 4 | 3 (Yes) | Skip (not start) | - |
| 1 | 0 (No) | Start Streak | 4 (1,2,3,4) |
Visual:
[1] -> [2] -> [3] -> [4] (Sequence identified from 1)
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.