Best time to buy and sell
- CH1 buy
- CH2 sell
The window runs from buy day to sell day. Buy moves to any cheaper day.
Step through it →A sliding window grows on the right and shrinks on the left, so each element enters and leaves once instead of being scanned again.
Right adds one character. If that makes a repeat, left jumps past the earlier copy before anything is measured. So every length the stage reads is a valid window's.
Each input here has tripped up a version of this code. The stage runs the one that gets it right.
The last 'a' was seen at 0, before left. Jumping left to 1 would move it backwards and let 'bb' back in. It jumps only for a sighting inside the window.
The window runs from buy day to sell day. Buy moves to any cheaper day.
Step through it →The window never shrinks. It slides when more than k letters would need changing.
Step through it →Grow until the window covers t, then shrink while it still does.
Step through it →The same algorithm in plain Python. The lit line is the one the current frame came from.
def length_of_longest_substring(s): left = 0 best = 0 last_index = {} for right in range(len(s)): c = s[right] if c in last_index and last_index[c] >= left: left = last_index[c] + 1 last_index[c] = right best = max(best, right - left + 1) return best