Longest Substring Without Repeating Characters
Given a string s, return the length of the longest substring without repeating characters . Grow a window on the right and shrink from the left whenever a duplicate enters, so the window never holds the same character twice.
Constraints
- 0 ≤ s.length ≤ 5 × 104
- s consists of English letters, digits, symbols and spaces
Example
s = "abcabcbb"3Explanation The answer is "abc", with length 3.
Expand until a duplicate, then shrink left
Window [a]; best = 1.
What happens in this step
window = [0, 0] ("a")
before: seen = {}, best = 0
add s[0] = 'a' → seen = {a}
seen now holds just 'a'; the window length 1 becomes the new best.Steps to visualize
- Grow right and add each new character into a seen set.
- When the new char is already in the set, shrink left until the duplicate is gone.
- After each add, the window holds only unique characters.
- Track the longest valid window length as best.
- Continue until right reaches the end of the string.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Window [a]; best = 1.
What happens in this step
window = [0, 0] ("a")
before: seen = {}, best = 0
add s[0] = 'a' → seen = {a}
seen now holds just 'a'; the window length 1 becomes the new best.Solution
function lengthOfLongestSubstring(s) {
const seen = new Set();
let left = 0;
let best = 0;
for (let right = 0; right < s.length; right++) {
const c = s[right];
while (seen.has(c)) {
seen.delete(s[left]);
left++;
}
seen.add(c);
best = Math.max(best, right - left + 1);
}
return best;
}- Time
- O(n)
- Space
- O(min(n, charset))
Test cases
| Input | Expected | Covers |
|---|---|---|
s = "abcabcbb" | 3 | Docstring example — longest unique window is "abc" |
s = "" | 0 | Empty string has length 0 |
s = "a" | 1 | Single character |
s = "abcdef" | 6 | Entire string is unique |
s = "bbbbb" | 1 | All identical characters |
s = "pwwkew" | 3 | Classic pwwkew case — "wke" |
s = "dvdf" | 3 | Must shrink past first d to take "vdf" |
s = "a b c a" | 3 | Spaces and repeats far apart |