Sliding window
About this lesson
Many problems ask for the best run of neighbouring items: the longest stretch, the largest sum of k numbers. A sliding window answers them in one pass. Watch a window slide over the string "abcbad": its right end takes in a new letter each step, and its left end lets letters go whenever one repeats, until it finds the longest substring with no repeated letter. The Software lessons "Strings: text in memory" and "Searching: linear and binary" cover indexing and lookup; "Two pointers" in this module is the same idea of two indices that only move forward.
Longest run of different letters
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.
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 stopRead the lesson step by step
Longest run of different letters
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.
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 stopA window with two ends
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.
line 2 seen = set() letters inside the window line 3 left = best = 0 line 4 for right, ch in enumerate(s): right = 0, 1, 2, ... the window is s[left..right], length right - left + 1 rule: no letter twice inside the window `ch in seen` is O(1) on average for a Python setGrow to the right
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 = 0, ch = 'a' line 5 'a' in seen → False line 8 seen.add('a') line 9 length 1, best = 1 right = 1, ch = 'b' line 5 'b' in seen → False line 8 seen.add('b') line 9 length 2, best = 2 right = 2, ch = 'c' line 5 'c' in seen → False line 8 seen.add('c') line 9 length 3, best = 3 window s[0..2] = "abc" seen = {'a', 'b', 'c'} best = 3A repeat: shrink from the left
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 = 3, ch = 'b' line 5 'b' in seen → True line 6 seen.remove('a') line 7 left = 1 line 5 'b' in seen → True line 6 seen.remove('b') line 7 left = 2 line 5 'b' in seen → False line 8 seen.add('b') line 9 length 2, best = 3 window s[2..3] = "cb" seen = {'c', 'b'} best = 3An old letter comes back
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 = 4, ch = 'a' line 5 'a' in seen → False line 8 seen.add('a') line 9 length 3, best = 3 window s[2..4] = "cba" seen = {'c', 'b', 'a'} best = 3A new record
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.
right = 5, ch = 'd' line 5 'd' in seen → False line 8 seen.add('d') line 9 length 4, best = 4 window s[2..5] = "cbad" seen = {'c', 'b', 'a', 'd'} best = 4The answer
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.
line 10 return best 4 longest_unique("abcbad") == 4 the window: s[2:6] = "cbad" brute force: best 4 after 21 substringsWhy it is O(n)
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).
adds: 6 (one per letter, as right moves) removes: 2 (at most one per letter, as left moves) total: 8 ≤ 2n = 12 aggregate count (as in CLRS ch. 16): left never passes right, so the while loop runs at most n times over the whole scan set lookups, adds and removes: O(1) on average total: O(n) time, O(k) extra space for k different lettersThe pattern, in general
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.
variable window (this lesson): for right in range(n): add s[right] while the window breaks the rule: drop s[left]; left += 1 record the window fixed window of k (for example the largest sum of k numbers): total += a[i] - a[i - k] one add, one drop: O(n), not O(nk) it works when shrinking a bad window can only help, so left never needs to move back
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01What does longest_unique return for "pwwkew"?
The window grows to "pw", then the second w forces left past both p and the first w. It then grows to "wke" (length 3); the last w is a repeat, so left drops the w at index 2 and the window becomes "kew", still length 3. So 3 is the best.
02When the new letter ch is already in seen, what does the while loop do?
Only the left end moves, one letter at a time. In the lesson, right = 3 brings a second b, so a and then the first b leave before the new b is added.
03There is a while loop inside the for loop. Why is the whole scan still O(n)?
Count all the moves of the run together: right moves n times and left at most n times. One pass of the for loop can move left several times, but the total is still at most 2n, and each set operation is O(1) on average.
04Why does the figure keep the letters of the window in a set?
A Python set is a hash table: `ch in seen` is O(1) on average. Without it, each step would scan the window, which costs up to its length.
05You want the largest sum of any 3 neighbouring numbers in a list. How does a fixed-size window update the sum when it slides one place?
With a fixed width both ends move together, so one add and one subtract keep the running total: about n steps instead of n × k.
Glossary
- Substring
- A run of neighbouring characters inside a string, such as "cba" inside "abcbad".
- Sliding window
- A run of neighbouring items marked by two indices, left and right, that both only move forward through a list or string.
- Variable-size window
- A window whose right end grows one item at a time and whose left end moves forward only when a rule is broken.
- Fixed-size window
- A window that always holds k items, so both ends move together, one item in and one item out.
- Set
- A collection that holds each item at most once and has no order. In Python, `x in s`, add and remove take O(1) time on average.
- Aggregate analysis
- Counting the cost of every operation over a whole run, rather than the worst case of one step, to bound the total.
Notes and sources
- 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.
- 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.
- 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.
- A fixed-size window keeps its width k, so both ends always move together. To find the largest sum of k neighbours, add the number entering and subtract the one leaving instead of re-adding all k: n steps instead of about n × k.
- longest_unique is real Python 3: longest_unique("abcbad") returns 4, longest_unique("") returns 0, and longest_unique("aaaa") returns 1.
- Python library: Set types, set and frozenset
- Python docs: Time complexity of built-in types
- Python library: enumerate()
- Sedgewick and Wayne, Algorithms 4th ed., §3.5 Searching Applications (sets)
- Sedgewick and Wayne, Algorithms 4th ed., §5.3 Substring Search
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 4: Hashing
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022): chapter 11 Hash Tables, chapter 16 Amortized Analysis
Quiz Unlocks after the last step.