1def longest_unique(s):2 seen = set()3 left = best = 04 for right, ch in enumerate(s):5 while ch in seen:6 seen.remove(s[left])7 left += 18 seen.add(ch)9 best = max(best, right - left + 1)10 return best[0]a[1]b[2]c[3]b[4]a[5]dsseen = set()best0LR[0]a[1]b[2]c[3]b[4]a[5]d
Code card: the function running; the highlighted line is the one being runSand mat: the window; block L is its left end, block R its right endTray: the set seen, the letters inside the windowBack row: the string s · front cell: best, the longest window so farThe string s = "abcbad" sits in the back row on a sand mat: the window, from block L to block R. R moves right one letter at a time and each new letter hops into the tray, the set seen. When a letter repeats, L moves right and letters leave the set until the repeat is gone. best ends at 4, the length of "cbad".

The problem

  1. 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.

Slide the window

Answer and cost

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.