Sliding window, step by step
Step the two pointers through a string and see why each character enters and leaves once.
Examples
1for right, ch in enumerate(s): 2 count[ch] += 1 3 while count[ch] > 1: 4 count[s[left]] -= 1; left += 1 5 best = max(best, right - left + 1)
1/17
a0b1c2a3b4c5b6b7
Start: left = 0, empty window, best = 0.
Window(empty)length 0
Best0""
Pointer moves0 / ≤ 16right 0/8 · left 0
count (the window's state)
Each pointer only moves forward: right 8 times, left at most 8, so at most 16 moves instead of checking all 36 substrings. That is why the scan is O(n).
How it's calculated · assumptions
moves = right (n) + left (≤ n) ≤ 2n → O(n) time · O(k) space for the counts (k = distinct characters)
Same algorithm as the concept's code template. The example strings are illustrative.