Longest substring without repeating characters
A sliding window with a dictionary of last-seen positions. Extend the right edge one character at a time; when a character repeats inside the current window, jump the left edge past its previous occurrence. Every character is visited once, so it is O(n).
Overview
Why brute force is quadratic
Checking every substring is O(n²) substrings, each needing a uniqueness test — O(n³) naively, O(n²) with a set per start. The waste is that each restart throws away everything the previous one learned.
The window keeps it. When the right edge advances, the answer for the new window is derived from the old one instead of recomputed.
Step through it
What to watch
- The right edge never goes backwards — that is what keeps it linear.
- On a repeat, the left edge jumps rather than creeping.
- A repeat that already fell off the left is ignored — watch
abba.
Say this out loud
"Sliding window with a last-seen map. Right edge always advances; on a repeat inside the window the left edge jumps past the old occurrence. O(n) time, O(k) space in the alphabet."