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 O(n) time.
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
Example 3:
Input: nums = [1,0,1,2]
Output: 3
✅ Step-by-Step Dry Run:
🔹 Step 1: Put all numbers into a set
We create this:
set = {100, 4, 200, 1, 3, 2}
So we can quickly check if a number exists (in O(1) time).
🔹 Step 2: Loop through each number in the array
🔸 First number: 100
-
Check if
99is in the set → ❌ No -
So
100is the start of a sequence -
Start counting:
-
101→ ❌ not in set → Stop
-
-
Sequence length = 1
-
longest = max(0, 1) = 1 🔸 Next:4-
Check if
3is in the set → ✅ Yes -
So
4is not a starting point → skip
🔸 Next:
200-
-
Check if
199is in the set → ❌ No -
So
200is a start of a sequence -
Check
201→ ❌ Not in set → Stop -
Sequence length = 1
-
longest = max(1, 1) = 1 🔸 Next:
1-
Check if
0is in the set → ❌ No -
So
1is a start of a sequence -
Start counting:
-
2→ ✅ -
3→ ✅ -
4→ ✅ -
5→ ❌ Stop
-
-
Sequence =
1, 2, 3, 4→ Length = 4 -
longest = max(1, 4) = 4
-
Next:
3-
Check if
2is in the set → ✅ Yes -
So
3is not the start → skip
-
Next: 2
-
Check if
1is in the set → ✅ Yes -
So
2is not the start → skip
Comments
Post a Comment