Sliding Window (LeetCode #5)
Sliding window is a two-pointer technique for contiguous ranges: a substring or subarray. You grow a window on the right and shrink it on the left until it satisfies some rule. Because each element enters and leaves the window once, a two-level loop collapses into one \(O(n)\) pass. The giveaway phrase is contiguous subarray or substring with longest, shortest, or maximum.
The technique
Keep a window [l, r] and an invariant that it is valid. Grow on the right; when it becomes invalid, shrink from the left until valid again.
def window(s):
l = 0
best = 0
state = {} # counts / set / sum describing the window
for r, ch in enumerate(s):
add(state, ch) # grow
while not valid(state): # shrink while invalid
remove(state, s[l])
l += 1
best = max(best, r - l + 1)
return best
Why it is \(O(n)\) despite the inner while. l only moves right, at most n times total, so the inner loop’s total work is bounded by n.
Fixed-size window is even simpler: add the new element, remove the one leaving the left.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\bfseries}]
\foreach \v [count=\i from 0] in {a,b,c,a,b,c,b,b} { \node[c, fill=blue!8] at (\i*0.66,0) {\v}; }
\draw[very thick, green!55!black, rounded corners=2pt] (-0.37,-0.35) rectangle (2.9,0.35);
\node[font=\scriptsize\ttfamily, text=green!45!black] at (-0.72,0) {l};
\node[font=\scriptsize\ttfamily, text=orange!75!black] at (3.25,0) {r};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (2.3,-0.7) {grow r; shrink l while invalid};
\end{tikzpicture}
Best Time to Buy and Sell Stock
The question. Buy on one day, sell on a later day; maximise profit.
Input: [7,1,5,3,6,4] -> 5 (buy 1, sell 6)
The idea. Track the cheapest price so far; the best profit selling today is today − cheapest.
Walk it through on [7, 1, 5, 3, 6, 4]:
| day | price | cheapest so far | profit if sold today | best |
|---|---|---|---|---|
| 0 | 7 | 7 | 0 | 0 |
| 1 | 1 | 1 | 0 | 0 |
| 2 | 5 | 1 | 4 | 4 |
| 3 | 3 | 1 | 2 | 4 |
| 4 | 6 | 1 | 5 | 5 |
| 5 | 4 | 1 | 3 | 5 |
def max_profit(prices):
buy = float("inf")
best = 0
for p in prices:
buy = min(buy, p)
best = max(best, p - buy)
return best
Why it works. buy is the minimum of all prices strictly before today, so p - buy is exactly the best profit obtainable by selling today. The maximum over all days is therefore the global answer, and the buy-before-sell rule is enforced for free because buy only ever looks backward.
Complexity. \(O(n)\) time, \(O(1)\) space.
Edge cases. Monotonically falling prices → 0 (we simply never buy). One day → 0. A single best day in the middle is found because best is carried forward.
Longest Substring Without Repeating Characters
The question. Length of the longest substring with no repeated character.
Input: "abcabcbb" -> 3 ("abc")
The idea. The window is valid iff it has no duplicates. When the new character is already present, shrink from the left until it leaves.
Walk it through on "abcabcbb":
r |
char | duplicate? | l after shrinking |
window | best |
|---|---|---|---|---|---|
| 0 | a | no | 0 | a |
1 |
| 1 | b | no | 0 | ab |
2 |
| 2 | c | no | 0 | abc |
3 |
| 3 | a | yes | 1 | bca |
3 |
| 4 | b | yes | 2 | cab |
3 |
| 5 | c | yes | 3 | abc |
3 |
| 6 | b | yes | 5 | cb |
3 |
| 7 | b | yes | 7 | b |
3 |
def longest_unique(s):
seen, l, best = set(), 0, 0
for r, ch in enumerate(s):
while ch in seen:
seen.remove(s[l]); l += 1
seen.add(ch)
best = max(best, r - l + 1)
return best
Why it works. seen always holds exactly the characters in [l, r], so when ch is already in seen the window is invalid and we must drop characters from the left until the duplicate leaves. Each character is added once and removed at most once, so the inner while costs \(O(n)\) in total.
Edge cases. Empty string → 0. All identical ("bbbb") → 1. All distinct → n.
Longest Repeating Character Replacement
The question. Change at most k characters; return the longest substring that can become all one letter.
Input: "AABABBA", k = 1 -> 4
The idea. A window can become all one letter when the non-majority characters are ≤ k:
\[ \text{window length} - \text{count of the most frequent letter} \le k \]
Walk it through on "AABABBA", k = 1. The window [l, r] and its letter counts:
r |
char | counts | maxf |
length | length − maxf | action | best |
|---|---|---|---|---|---|---|---|
| 0 | A | A:1 | 1 | 1 | 0 | valid | 1 |
| 1 | A | A:2 | 2 | 2 | 0 | valid | 2 |
| 2 | B | A:2,B:1 | 2 | 3 | 1 | valid | 3 |
| 3 | A | A:3,B:1 | 3 | 4 | 1 | valid | 4 |
| 4 | B | A:3,B:2 | 3 | 5 | 2 | shrink l to 2 |
4 |
| 5 | B | A:1,B:3 | 3 | 4 | 1 | valid | 4 |
| 6 | A | A:2,B:3 | 3 | 5 | 2 | shrink l to 4 |
4 |
def character_replacement(s, k):
counts, l, best, maxf = {}, 0, 0, 0
for r, ch in enumerate(s):
counts[ch] = counts.get(ch, 0) + 1
maxf = max(maxf, counts[ch])
while (r - l + 1) - maxf > k:
counts[s[l]] -= 1; l += 1
best = max(best, r - l + 1)
return best
Why it works. length − maxf is the number of characters that are not the window’s majority letter — exactly the number we would have to replace to make the window uniform. If that is at most k, the window is achievable. Shrinking from the left is safe because once a window is too costly, extending it on the right can only add more non-majority characters.
Why maxf never decreases. It records the largest count seen anywhere so far, not necessarily in the current window. Because it only grows, the window length never shrinks below the best answer already found; the sizes we record are still the true maxima, and letting maxf lag only makes the shrink condition fire less often. The whole scan is therefore \(O(n)\).
Edge cases. k = 0 → the longest run of one letter. k ≥ len(s) → the whole string. Empty string → 0.
Permutation in String
The question. Return True if s2 contains a permutation of s1 as a contiguous substring.
Input: s1 = "ab", s2 = "eidbaooo"
Output: True ("ba" is a permutation of "ab")
The idea. A permutation of s1 has exactly the same character counts as s1, and its length is fixed (len(s1)). So slide a fixed-size window of that length across s2 and ask whether its counts equal s1’s.
Walk it through on s1="ab", s2="eidbaooo". count(s1) = {a:1, b:1}. Windows of size 2: ei, id, db, ba — ba has counts {b:1, a:1} → match → True.
Use a running count: add the new character, remove the one leaving the window, and track how many characters currently match the target.
from collections import Counter
def check_inclusion(s1, s2):
if len(s1) > len(s2):
return False
need = Counter(s1)
window = Counter(s2[:len(s1)])
if window == need:
return True
for i in range(len(s1), len(s2)):
window[s2[i]] += 1 # add the incoming character
left = s2[i - len(s1)]
window[left] -= 1 # remove the outgoing character
if window[left] == 0:
del window[left]
if window == need:
return True
return False
Why compare whole counters? The alphabet is fixed (26 lowercase), so the comparison is effectively \(O(1)\) per window, giving \(O(n)\) total.
\(O(n)\) time, \(O(k)\) space.
Minimum Window Substring
The question. Find the shortest substring of s containing every character of t (with multiplicities).
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
The idea. Expand the right until the window covers t; then shrink the left as far as possible while still covering, recording the smallest window. Track coverage with formed (how many required characters reached their needed count) and compare to required.
from collections import Counter
def min_window(s, t):
need = Counter(t)
have, l, formed = Counter(), 0, 0
best = (0, float("inf"))
required = len(need)
for r, ch in enumerate(s):
if ch in need:
have[ch] += 1
if have[ch] == need[ch]:
formed += 1
while formed == required:
if r - l < best[1] - best[0]:
best = (l, r)
if s[l] in need:
have[s[l]] -= 1
if have[s[l]] < need[s[l]]:
formed -= 1
l += 1
return s[best[0]:best[1] + 1] if best[1] < len(s) else ""
Walk it through on s = "ADOBECODEBANC", t = "ABC" (so need = {A:1, B:1, C:1}, required = 3). Only the moments when the window becomes valid (formed == 3) matter:
r |
character added | window when first covered | shrink until | best window |
|---|---|---|---|---|
| 5 | C | ADOBEC (len 6) |
dropping A loses coverage → l = 1 |
ADOBEC (6) |
| 10 | A | DOBECODEBA (len 10) |
shrink to CODEBA (len 6) |
CODEBA (6) |
| 12 | C | ODEBANC (len 7) |
shrink to BANC (len 4) |
BANC (4) |
At r = 12 the left pointer walks past O, D, E (not needed) and stops at B, leaving the four-character window BANC; a further shrink would drop the B and lose coverage, so the loop exits and BANC is the answer.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.55cm, minimum height=0.5cm, font=\scriptsize\ttfamily}]
\foreach \v [count=\i from 0] in {O,D,E,B,A,N,C} { \node[c, fill=blue!8] at (\i*0.61,0) {\v}; }
\draw[very thick, green!55!black, rounded corners=2pt] (-0.33,-0.3) rectangle (3.98,0.3);
\draw[very thick, orange!80!black, rounded corners=2pt] (1.5,-0.3) rectangle (3.98,0.3);
\node[font=\scriptsize\ttfamily, text=green!45!black, anchor=north] at (1.8,-0.4) {covered};
\node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=north] at (2.75,-0.75) {shrink to BANC};
\end{tikzpicture}
Why it works. formed counts how many distinct characters of t currently meet their required multiplicity. The window is valid exactly when formed == required, so the while shrinks while valid and records the window just before each removal. Any shorter valid window must end at some r, and at that r we shrink as far as coverage allows, so the optimum cannot be missed.
Why formed, not a full comparison. Comparing have with need each step would cost \(O(k)\) per index. Tracking only the characters that newly meet (or fall below) their target makes every increment/decrement \(O(1)\), so the scan is \(O(n)\).
Complexity. \(O(n + m)\) time for n = len(s), m = len(t); \(O(k)\) space for the distinct characters of t.
Edge cases. t longer than s → "". t empty → "". Characters of t repeated (t = "AABC") are handled because need counts multiplicities rather than mere presence.
Sliding Window Maximum
The question. Return the maximum of every window of size k.
Input: [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
The idea. Keep a monotonic deque of indices whose values are decreasing. The front is the window maximum. When a new value arrives, pop from the back every value smaller than it (they can never be the maximum again), then push it. Remove the front if it fell out of the window.
Walk it through. For [1,3,-1], the deque holds index 1 (value 3) at the front → max 3. After sliding, 5 pops everything smaller and leads.
from collections import deque
def max_sliding_window(nums, k):
dq, out = deque(), []
for i, x in enumerate(nums):
while dq and nums[dq[-1]] <= x:
dq.pop()
dq.append(i)
if dq[0] <= i - k:
dq.popleft()
if i >= k - 1:
out.append(nums[dq[0]])
return out
\(O(n)\) time, \(O(k)\) space.
Pitfalls
- Resetting the window instead of shrinking. Restarting
latrbreaks the amortized bound. - Forgetting to remove the left element. The window state must stay in sync with
[l, r]. - Comparing counters inefficiently. With a fixed alphabet it is \(O(1)\); otherwise hash the counts.
- Recomputing the window max each step. Use a monotonic deque.
- Assuming positivity for “longest subarray sum”. Negatives break the monotonicity.
Why is a sliding window amortized \(O(n)\)? Why does Permutation in String use a fixed-size window?
ASolution
Each index is added once and removed at most once. A permutation of s1 is exactly a substring whose character counts match s1, and it has fixed length len(s1), so sliding a fixed-size window and comparing counts checks every candidate in \(O(n)\).
Next: Linked List (LeetCode #6) — pointers, reversal, and cycle detection.