Problem:
Given a string s, find the length of the longest substring without repeating characters.
Example:
Input: "abcabcbb"
Output: 3
Explanation: "abc"
🔥 Best Approach (HashMap Jump Optimization)
Instead of removing one by one,
jump left directly to the correct position.
⚙️ Algorithm
Use hashmap<char, last_index>
For each character:
if already seen inside current window:
move left = last_index + 1
update answer
update last seen index
💻 C++ Optimal Solution
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> lastSeen;
int left = 0;
int ans = 0;
for (int right = 0; right < s.size(); right++) {
char ch = s[right];
// duplicate inside current window
if (lastSeen.count(ch)) {
left = max(left, lastSeen[ch] + 1);
}
lastSeen[ch] = right;
ans = max(ans, right - left + 1);
}
return ans;
}
};
🔍 Dry Run
Input:
"abcabcbb"
| right | char | left | window | ans |
|---|---|---|---|---|
| 0 | a | 0 | a | 1 |
| 1 | b | 0 | ab | 2 |
| 2 | c | 0 | abc | 3 |
| 3 | a | 1 | bca | 3 |
| 4 | b | 2 | cab | 3 |
| 5 | c | 3 | abc | 3 |
| 6 | b | 5 | cb | 3 |
| 7 | b | 7 | b | 3 |
⏱️ Complexity
Optimal
- Time: O(n)
- Space: O(charset)
Because:
- Each character processed once
leftnever moves backward
