Use a variable-size sliding window to find the longest unique substring.
Use the editor below to find the length of the longest substring with no duplicate characters.
Keep every character in the window unique
Expand from the right and shrink from the left only when the new character is already present. Handle empty strings, spaces, and repetitions after a gap.
Submit your implementation when it passes the examples.
Given a string s, return the length of its longest contiguous substring with no repeated characters.
The substring must use adjacent characters from the original string.
0 ≤ s.length ≤ 50,000Results appear here after a run.
The left and right indexes mark the edges of the window, and a set tracks its characters. If s[right] is already in the set, remove s[left] and move left forward until the duplicate is gone.
Add s[right] and use right - left + 1 to update the longest valid length. For "abba", the second b requires removing both the old a and the old b before the new b can enter.
function lengthOfLongestSubstring(s) {
const window = new Set();
let left = 0;
let longest = 0;
for (let right = 0; right < s.length; right++) {
while (window.has(s[right])) {
window.delete(s[left]);
left++;
}
window.add(s[right]);
longest = Math.max(longest, right - left + 1);
}
return longest;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | Average O(n) | Each character enters and leaves the window at most once. |
| Auxiliary space | O(k) | Here k is the maximum number of distinct characters in a valid window. |