1. Window contents
A Set holds the distinct characters in the current window.
const seen = new Set()Typorithm · medium
Step 1 of 8 · intro card
Sliding Window
Grow the window to the right; when a repeat appears, shrink from the left until the window holds unique characters.
The window must contain only distinct characters at all times.
Expanding right adds a character; if it duplicates one already inside, shrink from the left until it is removed.
The answer is the maximum window width seen during the sweep.
Set tracks the window's characters.
Shrink left until no duplicate.
Window width = right - left + 1.
function lengthOfLongestSubstring(s) {
const seen = new Set();
let left = 0;
let best = 0;
for (let right = 0; right < s.length; right += 1) {
while (seen.has(s[right])) {
seen.delete(s[left]);
left += 1;
}
seen.add(s[right]);
best = Math.max(best, right - left + 1);
}
return best;
}Connect each part of the code to the concept before you type.
A Set holds the distinct characters in the current window.
const seen = new Set()Drop characters from the left until the duplicate is gone.
while (seen.has(s[right])) {
seen.delete(s[left]);
left += 1;
}Add the new character once the window is valid.
seen.add(s[right])Track the longest valid window width.
best = Math.max(best, right - left + 1)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.