Keep a window over a contiguous part of the array. Slide it right by adding one item and dropping one, updating the answer as you go instead of recomputing.
Used for
Window "a", length 1
best so far: 1
Window "abc", length 3
best so far: 3
The new "a" repeats the first one
best so far: 3
Window "bca", length 3
best so far: 3
Window "bcadef", length 6
best so far: 6
Add "p". Window "p", length 1.
best so far: 1
Move 1 of 12
Step 1 of 6
Goal: find the longest stretch of letters with no letter repeated. Checking every stretch is slow. Instead keep one window over the string and only ever slide it forward.
Step 2 of 6
Grow the window to the right while each new letter is different. "abc" has no repeats, so its length, 3, is the best so far.
Step 3 of 6
The next letter is "a", but the window already has an "a". The window is no longer valid.
Step 4 of 6
Fix it by shrinking from the left until the repeat is gone. Dropping the first "a" leaves "bca", valid again.
Step 5 of 6
Keep growing: add "d", "e", "f". The best is now "bcadef", length 6. The left edge and right edge only ever move forward, so each letter is added once and dropped at most once. This is called a sliding window.
Step 6 of 6
Your turn. Pick a word and press Next to watch the window grow and shrink.
function longestUnique(s) { const seen = new Map(); let best = 0, left = 0; for (let right = 0; right < s.length; right++) { if (seen.get(s[right]) >= left) left = seen.get(s[right]) + 1; seen.set(s[right], right); best = Math.max(best, right - left + 1); } return best;}