Longest Substring Without Repeating Characters
Difficulty: Medium
Given a string, find the length of the longest substring (a contiguous run of characters) with no repeated characters.
Examples
Input: s = "abcabcbb"
Output: 3
The longest run with no repeats is "abc", which has length 3.
Input: s = "bbbbb"
Output: 1
Every character repeats immediately, so the best you can do is a single character, "b".
Input: s = "pwwkew"
Output: 3
"wke" is the longest substring without repeats. Note "pwke" is not a valid answer because it is not contiguous in the original string.
Constraints
0 <= s.length <= 5 * 10^4
s consists of English letters, digits, symbols, and spaces.
Approach
Brute force checks every substring for repeats. Substrings overlap heavily, so that's a lot of repeated scanning.
Use a sliding window instead. Pointers left and right mark the current substring, and a set holds its characters. Move right forward one step at a time, adding characters to the set.
If the new character is already in the set, shrink from the left until the duplicate is gone. The window is then duplicate-free, so its length is a candidate answer. Each character enters and leaves the window at most once, so it's a single pass.
Solutions
Brute Force — Check Every Substring
Try every start position and extend until a character repeats. Simple, but re-scans overlapping substrings many times.
function lengthOfLongestSubstring(s) {
let best = 0;
for (let start = 0; start < s.length; start++) {
const seen = new Set();
for (let end = start; end < s.length; end++) {
if (seen.has(s[end])) {
break;
}
seen.add(s[end]);
best = Math.max(best, end - start + 1);
}
}
return best;
}Time: O(n²) · Space: O(min(n, alphabet size))
Optimal — Sliding Window with a Set
Move the right edge forward. If the new character is already in the window, shrink from the left until it isn't, then continue.
function lengthOfLongestSubstring(s) {
const window = new Set();
let left = 0;
let best = 0;
for (let right = 0; right < s.length; right++) {
while (window.has(s[right])) {
window.delete(s[left]);
left++;
}
window.add(s[right]);
best = Math.max(best, right - left + 1);
}
return best;
}Time: O(n) · Space: O(min(n, alphabet size))