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
99
is in the set → ❌ No -
So
100
is the start of a sequence -
Start counting:
-
101
→ ❌ not in set → Stop
-
-
Sequence length = 1
-
longest = max(0, 1) = 1
🔸 Next:
4
-
Check if
3
is in the set → ✅ Yes -
So
4
is not a starting point → skip
🔸 Next:
200
-
-
Check if
199
is in the set → ❌ No -
So
200
is a start of a sequence -
Check
201
→ ❌ Not in set → Stop -
Sequence length = 1
-
longest = max(1, 1) = 1
🔸 Next:
1
-
Check if
0
is in the set → ❌ No -
So
1
is 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
2
is in the set → ✅ Yes -
So
3
is not the start → skip
-
Next: 2
-
Check if
1
is in the set → ✅ Yes -
So
2
is not the start → skip
Comments
Post a Comment