Pattern GuideThe Sliding Window
Algorithm Pattern

The Sliding Window

"The magic of incremental updates. Never restart what you can reuse."

10 min read
Fundamental to Medium
Efficiency: O(N) Time
01
SIGNALS

Pattern Signals

Recognizing when to use the Sliding Window pattern is half the battle. When reading a question, look for these specific indicators:

🔎 Pattern Signals (When to use it?)

  • 📏
    Contiguous sequence: The problem mentions looking at contiguous subarrays, substrings, or sliding blocks. It never asks about non-contiguous combinations.
  • 📊
    Constraint boundaries: You need to find the longest substring with K unique characters, the shortest subarray with a target sum, or the maximum average of size K.
  • Optimal time constraints: A naive solution runs in quadratic time O(N x K) or O(N²), but target constraints require a linear O(N) runtime.
02
CORE INTUITION

The Power of State Reuse

🪟

Avoiding Duplicate Work

A very common problem in programming is needing to examine a small, connected subgroup of items within a much larger list. For example, trying to find the highest total you can get by adding 3 numbers that are right next to each other in a massive array.

The naive way to solve this is to look at the first 3 numbers and add them up. Then, shift over by one position, grab the next 3 numbers, and add them all up from scratch again. If you keep doing this, you are constantly recalculating the same numbers over and over!

The Sliding Window pattern solves this by keeping a running total (or running state) of your current "window". When the window moves forward by one spot, you don't calculate everything from scratch. You simply add the new element that just entered the front of the window, and subtract the old element that just fell out the back of the window.

Key Takeaway: By only updating the small differences—what just arrived and what just left—you turn a slow, repetitive calculation into a lightning-fast single pass. It reduces the workload from quadratic O(N x K) to linear O(N).
03
VISUALIZATION

Visualizing Efficiency

Notice how the Optimized approach never restarts. It simply slides, adjusting only the "delta" (the change) at each step.

INDEX 0
1
+
INDEX 1
2
+
INDEX 2
3
+
INDEX 3
4
INDEX 4
5
INDEX 5
6
Mode
DELTA UPDATING
Active Sum
6
Ops So Far
+3 / −0

Initial window [0,1,2]: add all 3 once: 1 + 2 + 3 = 6

1 / 4
04
FIXED WINDOW

Fixed-Size Window Archetype

A Fixed-Size Window maintains a constant range width of exactly K. As the window expands on the right, it immediately contracts on the left to maintain size. This is useful for looking at subsegment averages, fixed anagram patterns, or running sequences.

Fixed Trace Demo: Max Sum Subarray of size K = 3

0
2
L,R
1
1
2
5
3
1
4
3
5
2
function maxSubarraySum(arr, k) {
let left = 0, sum = 0, maxSum = 0;
for (let right = 0; right < arr.length; right++) {
sum += arr[right]; // 1️⃣ Expand
if (right - left + 1 === k) {
maxSum = Math.max(maxSum, sum); // 2️⃣ Record
sum -= arr[left]; // 3️⃣ Shrink
left++; // 4️⃣ Slide
}
}
return maxSum;
}
Variables Monitor
left:0
right:0
sum:0
maxSum:0
Initialize left pointer to 0, running sum to 0, and maxSum result tracker to 0.

Strategy Blueprint

1️⃣
ExpandAdd arr[right] to incorporate the entering element.
2️⃣
ConditionCheck if the active window width reaches size K.
3️⃣
Record / EvaluateCompare and update maxSum with the current window sum.
4️⃣
Slide windowSubtract arr[left] from sum, and increment left forward.
🎯 Target Scenario Signals:
Max/Min Subarray SumAnagram matchingFixed-length sequences
fixed_window.js
1
let left = 0;
2
let state = initializeState();
3
let result = initializeResult();
4
5
for (let right = 0; right < arr.length; right++) {
6
// 1️⃣ Expand
7
add(state, arr[right]);
8
9
// 2️⃣ Condition: When window reaches size K
10
if (right - left + 1 === k) {
11
// 3️⃣ Record / Evaluate
12
result = updateResult(result, state);
13
14
// 4️⃣ Slide window
15
remove(state, arr[left]);
16
left++;
17
}
18
}
05
VARIABLE WINDOW

Variable-Size Window Archetype

A Variable-Size Window grows and shrinks dynamically under validation rules. The right pointer scans forward to expand the window. If the state becomes invalid (e.g., sum exceeds target limit, or duplicates are found), the left pointer contracts forward until the window becomes valid again.

Variable Trace Demo: Longest Subarray with Sum ≤ 7

Array: [2, 5, 2, 1, 6]
Limit: 7
0
2
L,R
1
5
2
2
3
1
4
6
function longestSubarray(arr, limit) {
let left = 0, sum = 0, maxLen = 0;
for (let right = 0; right < arr.length; right++) {
sum += arr[right]; // 1️⃣ Expand
while (sum > limit) {
sum -= arr[left]; // 2️⃣ Shrink
left++; // 3️⃣ Contract
}
maxLen = Math.max(maxLen, right - left + 1); // 4️⃣ Record
}
return maxLen;
}
Variables Monitor
left:0
right:0
sum:0
maxLen:0
Initialize left pointer, running sum, and maxLen tracker to 0.

Strategy Blueprint

1️⃣
ExpandAdd arr[right] to expand the active window.
2️⃣
ShrinkSubtract arr[left] from sum while sum > limit.
3️⃣
ContractIncrement left to shrink the active window frame.
4️⃣
Record / OptimizeRecord the maximum valid length (right - left + 1).
🎯 Target Scenario Signals:
Longest substringMin window containing subSubarray sums <= limit
variable_window.js
1
let left = 0;
2
let state = emptyState();
3
let result = 0;
4
5
for (let right = 0; right < arr.length; right++) {
6
// 1️⃣ Expand
7
addToState(state, arr[right]);
8
9
// 2️⃣ Condition: While invalid
10
while (!isValid(state)) {
11
// 3️⃣ Contract
12
removeFromState(state, arr[left]);
13
left++;
14
}
15
16
// 4️⃣ Record / Optimize
17
result = optimize(result, right - left + 1);
18
}
06
ANALYSIS

Performance Dashboard

TIME EFFICIENCY

O(N)
LINEAR SPEED

Each element is processed exactly twice (once entering on the right, once leaving on the left), making it radically faster than checking every combination.

THE INTUITION

1
Explorer
We move the right boundary forward to scan new values.
2
Monotonicity
For positive numbers, adding items strictly increases the total, establishing a predictable trend.
3
Repair
When constraints fail, advancing the left boundary is the only way to return to a valid state.
🚫

CRITICAL: When it Fails

Sliding Window fails with negative numbers. If subtracting an item makes the sum bigger, the window loses its clear "direction" and doesn't know how to repair itself.

07
CHEAT SHEET

Summary Comparison

Window StyleConstraint ConditionPointers SetupTime / Space Complexity
Fixed SizeSize is strictly Kright expands, left shifts when size matches KO(N) / O(1)
Variable SizeLength adjusts dynamicallyright expands, left contracts while invalidO(N) / O(1)
08
PRACTICE

Ready to Practice with Visual Simulations?

Max Sum Subarray of Size KEasy
Longest Substring Without Repeating CharactersMedium
Minimum Size Subarray SumMedium
Minimum Window SubstringHard

"Add from the right, check the rule, and shrink from the left."