Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get a string s. A substring is a block of consecutive characters, so "wke" is a substring of "pwwkew" but "pwke" is not (that's a subsequence). Return the length of the longest substring in which every character is different.
Constraints that matter: s has up to 5·10⁴ characters, which can be letters, digits, symbols and spaces. It can also be empty.
Example: s = "pwwkew" → 3. Both "wke" and "kew" have no repeats. Nothing of length 4 works.
Start with brute force
For every start i, extend the end j one character at a time, keeping a set of what you've seen. Stop as soon as s[j] is already in the set, because every longer substring from i has the same repeat. Track the longest.
That's O(n²) time in the worst case. For n = 5·10⁴ that's up to 2.5·10⁹ steps, which is too slow. The waste is easy to spot: when you move from start i to start i + 1, you throw the set away and rebuild almost the same thing.
Building the intuition
Take "abcabcbb". From start 0 the brute force reads a, b, c, then hits the second a and stops. Then it starts again at index 1 and reads b, c, a... But it already knew "bc" had no repeats. Why read it again?
Here's the key fact: if a window has no repeats, every smaller window inside it has no repeats either. So when you can't extend a window, you don't need to start over. Just drop characters from the left until the window is valid again, then keep extending to the right.
How much do you drop? When the new character c is already in the window, the window is broken because of the old copy of c. Any window that still includes that old copy is broken too. So move left forward, removing characters from the set, until the old c has left. Then add the new c.
So you have two pointers that only ever move forward, and a set describing exactly what's between them. The rule that's always true between steps is called the invariant. Here it's "the window s[left..right] has no repeats". Grow right, and shrink left while the invariant is broken. That's the variable sliding window, the main template of this stage.
The optimal approach
- Set
window = {}(a set),left = 0andbest = 0. - For each
rightwith characterc = s[right]:- while
cis inwindow, removes[left]fromwindowand doleft += 1; - add
ctowindow; best = max(best, right − left + 1).
- while
- Return
best.
The subtle detail: the while loop removes characters that are not c too. In "pwwkew", when the second w arrives at index 2 the window is "pw". You must remove p first and then the old w. You can't jump past a repeat without also giving up everything before it, because a substring must be contiguous.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
window = set() # the characters inside s[left..right]; all distinct
left = 0
best = 0
for right, c in enumerate(s):
# Adding c would create a repeat: shrink from the left until
# the old copy of c has left the window
while c in window:
window.remove(s[left])
left += 1
window.add(c)
best = max(best, right - left + 1) # the window is valid again
return bestclass Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> window; // the characters inside s[left..right]; all distinct
int left = 0;
int best = 0;
for (int right = 0; right < (int)s.size(); right++) {
char c = s[right];
// Adding c would create a repeat: shrink from the left until
// the old copy of c has left the window
while (window.count(c)) {
window.erase(s[left]);
left++;
}
window.insert(c);
best = max(best, right - left + 1); // the window is valid again
}
return best;
}
};class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> window = new HashSet<>(); // the characters inside s[left..right]; all distinct
int left = 0;
int best = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
// Adding c would create a repeat: shrink from the left until
// the old copy of c has left the window
while (window.contains(c)) {
window.remove(s.charAt(left));
left++;
}
window.add(c);
best = Math.max(best, right - left + 1); // the window is valid again
}
return best;
}
}/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function (s) {
const window = new Set(); // the characters inside s[left..right]; all distinct
let left = 0;
let best = 0;
for (let right = 0; right < s.length; right++) {
const c = s[right];
// Adding c would create a repeat: shrink from the left until
// the old copy of c has left the window
while (window.has(c)) {
window.delete(s[left]);
left++;
}
window.add(c);
best = Math.max(best, right - left + 1); // the window is valid again
}
return best;
};Dry run
s = "pwwkew"
| right | c | Shrinking (removed) | left | window after | Length | best |
|---|---|---|---|---|---|---|
| 0 | p | — | 0 | {p} | 1 | 1 |
| 1 | w | — | 0 | {p, w} | 2 | 2 |
| 2 | w | remove p, then w | 2 | {w} | 1 | 2 |
| 3 | k | — | 2 | {w, k} | 2 | 2 |
| 4 | e | — | 2 | {w, k, e} | 3 | 3 |
| 5 | w | remove w (index 2) | 3 | {k, e, w} | 3 | 3 |
The answer is 3.
Complexity
- Time: O(n).
rightmoves n times.leftalso moves at most n times in total over the whole run, since it never moves back. Each set operation is O(1) on average. So it's O(2n) = O(n). - Space: O(min(n, k)), where k is the size of the character set (at most 128 for ASCII). The window never holds two copies of anything.
Edge cases and traps
- Empty string.
""→0. The loop never runs. - A single space.
" "→1. Spaces are characters too. "abba". At the secondb, you removeaandb. At the finala, the window is{b}, soaisn't in it. The answer is 2. This trips up the "jump to last index" version (see the follow-ups).ifinstead ofwhile. Removing just one character on a repeat is wrong whenever the old copy isn't the leftmost character, as in"pww".- Recording before fixing. Update
bestonly after the window is valid again.
Say it in the interview
"I'll keep a sliding window with no repeated characters, plus a set of what's inside it. I move right one character at a time. If the new character is already in the set, I shrink from the left, removing characters until its old copy is gone. Then I add it and record the window length. Both pointers only move forward, so it's O(n) time, and the set holds at most one copy of each character."
Follow-ups interviewers ask
- "Can you skip the inner loop?" Store each character's last index in a map. On a repeat, jump
left = max(left, last[c] + 1). Themaxmatters: in"abba", the finala's last index is behindleft, and withoutmaxthe window would move backwards. - "At most k distinct characters instead of none repeated?" Same window, but keep counts in a map and shrink while the map has more than k keys.
- "Smallest window containing all of t's characters?" That's Minimum Window Substring in the bonus Hard DP & The Gauntlet stage. It's the same grow and shrink, but you shrink while the window is valid, to make it as short as possible.
Practise the same idea
This is Day 24 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free