Longest Substring Without Repeating Characters
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given a string s, return the length of the longest substring that has no repeated characters.
Understand the problem
- A substring is a piece of the string made of characters that sit next to each other, with nothing skipped. In
"pwwkew","wke"is a substring, but"pwke"is not (it skips aw). - No repeated characters means every character inside that piece appears only once.
- You return only the length, not the substring itself.
Example 1
Input: s = "abcabcbb"
Output: 3"abc" has no repeats. Any longer piece, like "abca", repeats a letter.
Example 2
Input: s = "bbbbb"
Output: 1Every piece longer than one character has two bs.
Example 3
Input: s = "pwwkew"
Output: 3"wke" works. "pwke" would be 4, but it's not a substring because the letters aren't next to each other in s.
Example 4
Input: s = ""
Output: 0Constraints
0 <= s.length <= 5 * 10^4scontains English letters, digits, symbols and spaces.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Slide a window over the string that never contains a repeated character: grow it on the right, and when a repeat appears, move the left edge just past the earlier copy.
The naive approach (and why it's slow)
Check every substring: for every start i and end j, test whether s[i..j] has repeats. There are about n²/2 substrings, and checking each one takes up to n steps, so it's O(n³). Even with a set to check faster, it's still O(n²).
The key insight
Most of that work is repeated. If "abc" has no repeats, then when we add the next letter, we only need to ask about that one new letter: is it already in the window?
So keep one window s[left..right] with a simple rule: no repeats inside.
- Grow: move
rightone step, adding a new character. - Fix: if that character is already in the window, move
leftforward until it's not. - Record: the window is valid now, so compare its length with the best so far.
To make the "fix" step instant, remember the last index where each character appeared (a hash map). If the new character was last seen at index p inside the window, the window must start at p + 1.
Step by step
s = "abcabcbb":
right | Char | Last seen at | Inside window? | left after | Window | Length | Best |
|---|---|---|---|---|---|---|---|
| 0 | a | never | no | 0 | a | 1 | 1 |
| 1 | b | never | no | 0 | ab | 2 | 2 |
| 2 | c | never | no | 0 | abc | 3 | 3 |
| 3 | a | 0 | yes | 1 | bca | 3 | 3 |
| 4 | b | 1 | yes | 2 | cab | 3 | 3 |
| 5 | c | 2 | yes | 3 | abc | 3 | 3 |
| 6 | b | 4 | yes | 5 | cb | 2 | 3 |
| 7 | b | 6 | yes | 7 | b | 1 | 3 |
Answer: 3.
Why max(left, p + 1)? Take s = "abba". At right = 3 (a), the last a was at index 0, but the window already starts at 2 (after the bb fix). That old a is outside the window, so it doesn't matter. Without max, we'd move left back to 1, and the window "bba" would contain two bs.
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n).
rightmoves through the string once, andleftonly ever jumps forward. - Memory: O(k), where
kis the number of different characters (at most the alphabet size).
Common mistakes
- Moving
leftbackward. Forgetting themaxlets an old, out-of-window sighting drag the window back over a repeat. - Updating "last seen" before using it. You need the previous index of the character, so read it first, then store the new index.
- Off-by-one in the length. A window from
lefttoright(both included) has lengthright - left + 1.
Going deeper
This "grow right, shrink left until valid" loop is the general sliding window template. You'll see the exact same shape in Longest Repeating Character Replacement and Minimum Window Substring, just with a different rule for "valid".
Reference solution
/**
* @param {string} s
* @return {number}
*/
export default function lengthOfLongestSubstring(s) {
// character -> the last index where we saw it
const lastSeen = new Map()
let left = 0 // the window is s[left..right], with no repeats inside
let best = 0
for (let right = 0; right < s.length; right++) {
// Read the previous sighting BEFORE storing the new one.
const previous = lastSeen.get(s[right])
// A repeat inside the window: start the window just after the old copy.
// max() ignores old sightings from before the window, so left never moves back.
if (previous !== undefined) left = Math.max(left, previous + 1)
lastSeen.set(s[right], right)
best = Math.max(best, right - left + 1) // window length, both ends included
}
return best
}export default function lengthOfLongestSubstring(s: string): number {
// character -> the last index where we saw it
const lastSeen = new Map<string, number>()
let left = 0 // the window is s[left..right], with no repeats inside
let best = 0
for (let right = 0; right < s.length; right++) {
// Read the previous sighting BEFORE storing the new one.
const previous = lastSeen.get(s[right])
// A repeat inside the window: start the window just after the old copy.
// max() ignores old sightings from before the window, so left never moves back.
if (previous !== undefined) left = Math.max(left, previous + 1)
lastSeen.set(s[right], right)
best = Math.max(best, right - left + 1) // window length, both ends included
}
return best
}def length_of_longest_substring(s: str) -> int:
# character -> the last index where we saw it
last_seen = {}
left = 0 # the window is s[left..right], with no repeats inside
best = 0
for right, char in enumerate(s):
# A repeat inside the window: start the window just after the old copy.
# max() ignores old sightings from before the window, so left never moves back.
if char in last_seen:
left = max(left, last_seen[char] + 1)
last_seen[char] = right
best = max(best, right - left + 1) # window length, both ends included
return best