26. Sliding Window
Keep a contiguous window [left, right] and slide it across the input, growing on the right and shrinking on the left, to answer ‘longest/shortest subarray or substring with property X’ in O(n).
How it works
For longest substring without repeating characters, extend right one character at a time. Remember the last index of each character. If the new character already appears inside the current window, jump left to just past that earlier copy. The window is then repeat-free again, and its length is a candidate answer.
Both pointers only move forward, so the total work is O(n) even though the window changes size.
Diagram
flowchart TD
A["Move right one step, read char"] --> B{"char seen inside window?"}
B -->|yes| C["left jumps past its previous index"] --> D
B -->|no| D["Record index of char"]
D --> E["best = max of best and window length"] --> A
Step-by-step trace
Input: Longest substring without repeats in abcabcbb.
| right | char | Repeat inside window? | left | Window | best |
|---|---|---|---|---|---|
| 0 | a | no | 0 | a |
1 |
| 1 | b | no | 0 | ab |
2 |
| 2 | c | no | 0 | abc |
3 |
| 3 | a | yes (at 0), left -> 1 | 1 | bca |
3 |
| 4 | b | yes (at 1), left -> 2 | 2 | cab |
3 |
| 5 | c | yes (at 2), left -> 3 | 3 | abc |
3 |
| 6 | b | yes (at 4), left -> 5 | 5 | cb |
3 |
| 7 | b | yes (at 6), left -> 7 | 7 | b |
3 |
Result: Answer: 3 (for example abc).
Complexity
| Operation | Time | Space |
|---|---|---|
| Variable-size window | O(n) | O(size of alphabet) |
| Fixed-size window of k | O(n) | O(1) to O(k) |
Python reference implementation
def longest_unique_substring(s):
"""Sliding window: length of the longest substring without repeated characters."""
last_seen = {}
left = best = 0
for right, ch in enumerate(s):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1 # jump past the previous copy
last_seen[ch] = right
best = max(best, right - left + 1)
return best
Common mistakes and tips
- Check
last_seen[ch] >= left; an old copy outside the window must not moveleftbackwards. - Fixed-size windows: add the entering item and subtract the leaving one instead of recomputing.
- Windows need monotonic behavior; with negative numbers in ‘subarray sum = k’, use prefix sums instead.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Two Pointers | Next: Prefix Sums (Subarray Sum Equals K) |