The problem
Find the longest substring of s = "abcbad" with no repeated letter. The answer is 4, for "cbad". Checking every substring means n(n+1)/2 = 21 of them for six letters, and scanning 56 letters: O(n³) work.
A window is a run of neighbouring letters, s[left..right]. Both ends start at 0. A set called seen holds the letters inside the window, so checking for a repeat is one quick lookup. best keeps the longest length so far.
Slide the window
right moves to 0, 1, 2. The letters a, b and c are not in seen, so the while loop never runs. Each letter is added and the window grows. Its length reaches 3, so best = 3.
right = 3 brings a second b, and b is in seen. So left moves: remove a, left = 1. b is still there: remove b, left = 2. Now add the new b. The window is "cb"; best stays 3.
right = 4 brings a. The first a left the window a step ago, so it is not in seen any more. Add it. The window is "cba", length 3, so best stays 3.
right = 5 brings d, which is new. Add it. The window "cbad" runs from left = 2 to right = 5: length 5 - 2 + 1 = 4, more than 3, so best = 4.
Answer and cost
The loop ends and longest_unique returns 4, the length of "cbad" = s[2:6]. Brute force agrees, after checking all 21 substrings. The window looked at each letter at most twice: once as it entered and, maybe, once as it left.
A while loop sits inside the for loop, yet both ends only move right. right moves n times and left at most n times. Here: 6 adds and 2 removes, at most 2n set changes. Each is O(1) on average, so the pass is O(n).
Use a sliding window when the answer is a run of neighbours. Grow the right end; while a rule is broken, shrink the left end. A fixed-size window of k moves both ends together: add the item that enters, drop the one that leaves.
What happens
;; step 1/9 · problem
s = "abcbad" n = 6
goal: 4 ("cbad" = s[2:6])
brute force: for every start i and end j, check s[i..j] for a repeat
substrings: n(n+1)/2 = 21
letters scanned: n(n+1)(n+2)/6 = 56
in general O(n³), or O(n²) with a set and an early stop
A Python set holds each item at most once and has no order. In the figure each letter block takes a fixed place in the tray (letter i in place (i + 2) mod 4), only so that blocks never have to shuffle and the final window reads in order; the places mean nothing to the set. The O(n) bound counts every move over the whole scan, not per iteration: one pass of the for loop can move left several times (right = 3 moved it twice), but left can never pass right, so it moves at most n times in total. Set lookups, adds and removes are O(1) on average because a set is a hash table. Python’s own docs note the worst case is O(n) per operation if many keys share a hash, which ordinary letters do not.