CodeArchon

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
0
b
1
c
2
a
3
b
4
c
5
b
6
b
7
MaplastSeen
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.

1def fresh_tasting_streak(s: str) -> int:
2 last_seen: dict[str, int] = {}
3 lo = best = 0
4 for hi, c in enumerate(s):
5 if c in last_seen and last_seen[c] >= lo:
6 lo = last_seen[c] + 1
7 last_seen[c] = hi
8 best = max(best, hi - lo + 1)
9 return best
Variables
lo=0
best=0

How to think about it

  1. Window = [lo..hi] of currently-unique characters.
  2. lastSeen[c] = index of the most recent occurrence of c.
  3. When s[hi] was last seen at some p ≥ lo, duplicate is inside the window — jump lo to p+1.
  4. 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 13
{"text":"abcabcbb","values":["a","b","c","a","b","c","b","b"]}

"abc" is the longest.

Example 21
{"text":"bbbbb","values":["b","b","b","b","b"]}
Example 33
{"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