Sliding Window
Maintain a contiguous window that grows and shrinks to find the best subarray or substring in a single O(n) pass.
A sliding window is a contiguous range [L, R] over an array or string. Instead of recomputing every subarray from scratch (O(n²) or worse), you slide the window: add the element entering on the right, remove the one leaving on the left, and update the answer incrementally. Each element enters and leaves at most once → O(n).
- The problem asks about a contiguous subarray or substring.
- You want the longest / shortest / count / maximum sum of windows satisfying a condition.
- The condition can be updated incrementally as elements enter and leave (counts, sums, distinct characters).
- Typical wording: "longest substring with at most k distinct…", "minimum window containing…", "maximum sum of size k".
Fixed-size window
int maxSumK(int[] a, int k) {
int sum = 0, best;
for (int i = 0; i < k; i++) sum += a[i];
best = sum;
for (int r = k; r < a.length; r++) {
sum += a[r] - a[r - k]; // add incoming, remove outgoing
best = Math.max(best, sum);
}
return best;
}def max_sum_k(a, k):
s = sum(a[:k])
best = s
for r in range(k, len(a)):
s += a[r] - a[r - k] # add incoming, remove outgoing
best = max(best, s)
return bestfunction maxSumK(a: number[], k: number): number {
let sum = 0;
for (let i = 0; i < k; i++) sum += a[i];
let best = sum;
for (let r = k; r < a.length; r++) {
sum += a[r] - a[r - k];
best = Math.max(best, sum);
}
return best;
}Variable-size window: the universal template
L = 0
for R in 0..n-1:
add a[R] to the window state
while the window is INVALID: # (for "longest" problems)
remove a[L] from the state; L++
update answer with window [L, R] # e.g. best = max(best, R - L + 1)For "shortest" problems flip it: while the window is VALID, record the answer and shrink.
int lengthOfLongestSubstring(String s) {
Map<Character, Integer> last = new HashMap<>(); // char → last index
int best = 0;
for (int l = 0, r = 0; r < s.length(); r++) {
char c = s.charAt(r);
if (last.containsKey(c) && last.get(c) >= l) l = last.get(c) + 1; // jump L past the duplicate
last.put(c, r);
best = Math.max(best, r - l + 1);
}
return best;
}def length_of_longest_substring(s):
last, l, best = {}, 0, 0
for r, c in enumerate(s):
if c in last and last[c] >= l:
l = last[c] + 1 # jump L past the duplicate
last[c] = r
best = max(best, r - l + 1)
return bestfunction lengthOfLongestSubstring(s: string): number {
const last = new Map<string, number>();
let l = 0, best = 0;
for (let r = 0; r < s.length; r++) {
const prev = last.get(s[r]);
if (prev !== undefined && prev >= l) l = prev + 1;
last.set(s[r], r);
best = Math.max(best, r - l + 1);
}
return best;
}String minWindow(String s, String t) {
int[] need = new int[128];
for (char c : t.toCharArray()) need[c]++;
int missing = t.length(), bestL = 0, bestLen = Integer.MAX_VALUE;
for (int l = 0, r = 0; r < s.length(); r++) {
if (need[s.charAt(r)]-- > 0) missing--; // a needed char entered
while (missing == 0) { // window VALID → try to shrink
if (r - l + 1 < bestLen) { bestLen = r - l + 1; bestL = l; }
if (++need[s.charAt(l++)] > 0) missing++; // a needed char left
}
}
return bestLen == Integer.MAX_VALUE ? "" : s.substring(bestL, bestL + bestLen);
}from collections import Counter
def min_window(s, t):
need = Counter(t)
missing, l, best = len(t), 0, (0, float("inf"))
for r, c in enumerate(s):
if need[c] > 0:
missing -= 1
need[c] -= 1
while missing == 0: # valid -> shrink
if r - l < best[1] - best[0]:
best = (l, r)
need[s[l]] += 1
if need[s[l]] > 0:
missing += 1
l += 1
return "" if best[1] == float("inf") else s[best[0]:best[1] + 1]function minWindow(s: string, t: string): string {
const need = new Map<string, number>();
for (const c of t) need.set(c, (need.get(c) ?? 0) + 1);
let missing = t.length, bestL = 0, bestLen = Infinity;
for (let l = 0, r = 0; r < s.length; r++) {
const c = s[r];
if ((need.get(c) ?? 0) > 0) missing--;
need.set(c, (need.get(c) ?? 0) - 1);
while (missing === 0) {
if (r - l + 1 < bestLen) { bestLen = r - l + 1; bestL = l; }
const d = s[l++];
need.set(d, need.get(d)! + 1);
if (need.get(d)! > 0) missing++;
}
}
return bestLen === Infinity ? "" : s.slice(bestL, bestL + bestLen);
}Window maximum with a monotonic deque
"Maximum of every window of size k" needs more than a sum. Keep a deque of indices whose values are decreasing: the front is always the window's maximum. Pop smaller values from the back before pushing; pop the front when it leaves the window. O(n).
int[] maxSlidingWindow(int[] a, int k) {
int[] res = new int[a.length - k + 1];
Deque<Integer> dq = new ArrayDeque<>(); // indices, values decreasing
for (int i = 0; i < a.length; i++) {
while (!dq.isEmpty() && a[dq.peekLast()] <= a[i]) dq.pollLast();
dq.offerLast(i);
if (dq.peekFirst() <= i - k) dq.pollFirst(); // left the window
if (i >= k - 1) res[i - k + 1] = a[dq.peekFirst()];
}
return res;
}from collections import deque
def max_sliding_window(a, k):
dq, res = deque(), []
for i, x in enumerate(a):
while dq and a[dq[-1]] <= x:
dq.pop()
dq.append(i)
if dq[0] <= i - k:
dq.popleft()
if i >= k - 1:
res.append(a[dq[0]])
return resfunction maxSlidingWindow(a: number[], k: number): number[] {
const dq: number[] = []; // a real deque is better; shift() is O(k) here
const res: number[] = [];
for (let i = 0; i < a.length; i++) {
while (dq.length && a[dq[dq.length - 1]] <= a[i]) dq.pop();
dq.push(i);
if (dq[0] <= i - k) dq.shift();
if (i >= k - 1) res.push(a[dq[0]]);
}
return res;
}- Maximum Average Subarray Ifixed windoweasy
- Best Time to Buy and Sell Stocktrack min so fareasy
- Longest Substring Without Repeating Charactersmedium
- Longest Repeating Character Replacementlen − maxFreq ≤ kmedium
- Permutation in Stringfixed window of countsmedium
- Find All Anagrams in a Stringmedium
- Minimum Size Subarray Sumshrink while validmedium
- Fruit Into Basketsat most 2 distinctmedium
- Max Consecutive Ones IIIat most k zerosmedium
- Subarrays with K Different IntegersatMost(k) − atMost(k−1)hard
- Minimum Window Substringhard
- Sliding Window Maximummonotonic dequehard
- Use for contiguous subarray/substring problems with incrementally maintainable state.
- Fixed window: add one, remove one. Variable window: expand R, shrink L while invalid (or while valid, for "shortest").
- Each index enters and leaves once → O(n).
- "Exactly k" = atMost(k) − atMost(k − 1).
- Window min/max needs a monotonic deque.
QWhy can't sliding window solve 'subarray sum equals k' with negative numbers?medium
With negatives, extending the window can decrease the sum and shrinking can increase it, so there's no monotonic rule for when to move L. Use prefix sums with a hash map of seen prefix sums instead: O(n).
QLongest repeating character replacement: why don't you decrease maxFreq when shrinking?hard
The answer only grows when a window with a higher maxFreq appears. A stale (too high) maxFreq can only keep the window the same size, never produce a wrong larger answer, so it's safe and keeps the algorithm O(n).