Module 1 · Lesson 4 · ~25 min
If two pointers turn O(n²) into O(n) on sorted arrays, sliding window does the same on contiguous subarrays and substrings. Once you see the move, you'll spot it in dozens of problems.
Walk along a row of houses with a window-frame held up to your eye that's exactly 3 houses wide. As you take one step forward, one house leaves the frame on the left and a new house enters on the right. You don't recount the houses inside — you just add the new one and remove the old one.
Watch it. The 4-element window slides across the array and we keep a running sum without rescanning.
You're given a window length k. You compute some aggregate (sum, max, count) over every contiguous window of length k.
# Max sum of any contiguous subarray of length k
def max_sum_window(arr, k):
s = sum(arr[:k])
best = s
for i in range(k, len(arr)):
s += arr[i] - arr[i - k] # add the new, drop the old
best = max(best, s)
return best
# O(n) time, O(1) space
// Max sum of any contiguous subarray of length k
function maxSumWindow(arr, k) {
let s = 0;
for (let i = 0; i < k; i++) s += arr[i];
let best = s;
for (let i = k; i < arr.length; i++) {
s += arr[i] - arr[i - k]; // add the new, drop the old
best = Math.max(best, s);
}
return best;
}
// O(n) time, O(1) space
// Max sum of any contiguous subarray of length k
function maxSumWindow(arr: number[], k: number): number {
let s = 0;
for (let i = 0; i < k; i++) s += arr[i];
let best = s;
for (let i = k; i < arr.length; i++) {
s += arr[i] - arr[i - k]; // add the new, drop the old
best = Math.max(best, s);
}
return best;
}
// O(n) time, O(1) space
The window grows and shrinks based on a condition. Two pointers (often called left and right) bound the current window. You expand right until the window violates the condition, then contract left until it's valid again.
# Longest substring without repeating characters
def longest_unique(s):
seen = {} # char → most recent index
left = best = 0
for right, ch in enumerate(s):
if ch in seen and seen[ch] >= left:
left = seen[ch] + 1 # jump left past the previous occurrence
seen[ch] = right
best = max(best, right - left + 1)
return best
# O(n) time, O(min(n, alphabet)) space
// Longest substring without repeating characters
function longestUnique(s) {
const seen = new Map(); // char → most recent index
let left = 0, best = 0;
for (let right = 0; right < s.length; right++) {
const ch = s[right];
if (seen.has(ch) && seen.get(ch) >= left) {
left = seen.get(ch) + 1; // jump left past the previous occurrence
}
seen.set(ch, right);
best = Math.max(best, right - left + 1);
}
return best;
}
// O(n) time, O(min(n, alphabet)) space
// Longest substring without repeating characters
function longestUnique(s: string): number {
const seen = new Map<string, number>(); // char → most recent index
let left = 0, best = 0;
for (let right = 0; right < s.length; right++) {
const ch = s[right];
if (seen.has(ch) && seen.get(ch)! >= left) {
left = seen.get(ch)! + 1; // jump left past the previous occurrence
}
seen.set(ch, right);
best = Math.max(best, right - left + 1);
}
return best;
}
// O(n) time, O(min(n, alphabet)) space
Variable-size is the harder flavor and the one interviewers love. The trick is naming the invariant you maintain about the window — it lets you decide when to expand and when to contract.
Watch it run on "longest substring with no repeated character" against "abcabcbb". The window expands right until a repeat appears, then contracts left until the invariant holds again.
"At every step, the window [left, right] contains (condition)." For longest-unique-substring: the invariant is "no repeated characters." When a new character violates it, contract from the left until it holds again.
| Problem shape | Window flavor | What you track |
|---|---|---|
| "Maximum / minimum sum of length-k subarray" | Fixed | running sum |
| "Average of every length-k window" | Fixed | running sum / k |
| "Maximum in every length-k window" | Fixed | monotonic deque (Module 2) |
| "Longest substring with property P" | Variable | state for P (counter, set) |
| "Smallest subarray with sum ≥ S" | Variable | running sum |
| "Number of substrings with property P" | Variable | state + count of valid right endpoints per left |
"This looks like a sliding-window problem — the window contents change incrementally as I move the right pointer. The brute force re-scans every window in O(n × k); the sliding window updates in O(1) per step, so total is O(n). I'll maintain the invariant that the window always satisfies (condition), expanding the right pointer and contracting the left when needed."
def min_subarray_len(target, nums):
left = s = 0
best = float('inf')
for right, x in enumerate(nums):
s += x
while s >= target:
best = min(best, right - left + 1)
s -= nums[left]
left += 1
return 0 if best == float('inf') else best
function minSubarrayLen(target, nums) {
let left = 0, s = 0, best = Infinity;
for (let right = 0; right < nums.length; right++) {
s += nums[right];
while (s >= target) {
best = Math.min(best, right - left + 1);
s -= nums[left++];
}
}
return best === Infinity ? 0 : best;
}
function minSubarrayLen(target: number, nums: number[]): number {
let left = 0, s = 0, best = Infinity;
for (let right = 0; right < nums.length; right++) {
s += nums[right];
while (s >= target) {
best = Math.min(best, right - left + 1);
s -= nums[left++];
}
}
return best === Infinity ? 0 : best;
}
right until the window meets the threshold; once it does, contract left as far as possible while still meeting it. Each pointer moves at most n times — total work O(n).