mediumSliding WindowAmazonGoogleMeta
Fresh Tasting Streak
A sommelier tastes bottles in order and keeps serving until a flavour repeats. What's the longest run of unique flavours?
Given a string `s`, return the length of the longest substring with no repeating characters.
Choose approach
a
0b
1c
2a
3b
4c
5b
6b
7MaplastSeen
empty
1/15
Narrationstep 1 of 15
Grow the window with hi. When a repeat lands at or after lo, jump lo past the duplicate. Track max window width.
Variables
lo=0
best=0
How to think about it
- Window = [lo..hi] of currently-unique characters.
- lastSeen[c] = index of the most recent occurrence of c.
- When s[hi] was last seen at some p ≥ lo, duplicate is inside the window — jump lo to p+1.
- Each character enters and leaves the window at most once → O(n).
Edge cases to catch in interview
- Empty string → 0.
- All unique → full length.
- All identical → 1.
Examples
Example 1
3{"text":"abcabcbb","values":["a","b","c","a","b","c","b","b"]}
"abc" is the longest.
Example 2
1{"text":"bbbbb","values":["b","b","b","b","b"]}
Example 3
3{"text":"pwwkew","values":["p","w","w","k","e","w"]}
"wke".
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed