Here’s the question link on Leetcode 3. Longest Substring Without Repeating Characters:
https://leetcode.com/problems/longest-substring-without-repeating-characters/description
Contents
Brute Force: Generate Every Substring
The simplest approach is to generate every possible substring and check whether it contains duplicate characters.
We can use a set to keep track of the characters in the current substring.
- Pick every starting index.
- Keep extending the substring one character at a time.
- If we find a character already in the set, stop extending.
- Otherwise, add it to the set and update our answer.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.size();
int ans = 0;
for(int i = 0; i < n; i++) {
unordered_set<char> seen;
for(int j = i; j < n; j++) {
if(seen.count(s[j]))
break;
seen.insert(s[j]);
ans = max(ans, j - i + 1);
}
}
return ans;
}
};
Optimal: Sliding Window + Hash Map O(n)
Instead of generating a new substring every time, let’s maintain a single window using two pointers: left and right.
The idea is simple:
- Move
rightforward to expand the window. - If we encounter a repeating character, move
leftjust past its previous occurrence. - Keep updating the maximum window length.
But how do we know where that character appeared previously?
We use a hash map to store the last index of every character.
Example
s = "abcabcbb"
We start with an empty window.
| Character | Window | Action | Max Length |
|---|---|---|---|
| a | a | Add a | 1 |
| b | ab | Add b | 2 |
| c | abc | Add c | 3 |
| a | bca | Move left past previous a | 3 |
| b | cab | Move left past previous b | 3 |
| c | abc | Move left past previous c | 3 |
| b | cb | Move left past previous b | 3 |
| b | b | Remove duplicate | 3 |
The answer is 3.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> mp;
int left = 0;
int ans = 0;
for(int right = 0; right < s.size(); right++) {
char c = s[right];
if(mp.find(c) != mp.end()) {
left = max(left, mp[c] + 1);
}
mp[c] = right;
ans = max(ans, right - left + 1);
}
return ans;
}
};