← Back to Patterns
Arrays & Sliding WindowMedium

Sliding Window

Maintain a moving subarray of variable or fixed size over a sequence.

How it works

Sliding Window avoids re-computing the entire subarray from scratch every time by maintaining a running state as the window moves. You keep a left and right boundary: expand right to include new elements, shrink left to restore a violated constraint. For fixed-size windows, you move both pointers forward together. For variable-size windows, the right pointer always advances one step; the left only advances when the window breaks the constraint. The "state" you maintain (sum, frequency map, distinct count) tells you in O(1) whether the current window is valid — making the overall algorithm O(n) instead of O(n²).

Interactive Playground

2151324window [0..2] sum = 8

Window [0..2], sum = 2+1+5 = 8. Track best.

Speed

When to use

  • Longest/shortest subarray satisfying a constraint
  • Maximum sum of k consecutive elements
  • Minimum window substring problems

Tips

1Decide upfront: fixed-size window or variable-size? Fixed = move left with right. Variable = shrink left only on violation.
2Maintain a hash map of character/element frequencies inside the window to track constraints in O(1).
3Update the answer AFTER adjusting the window to a valid state — never record an invalid window.
4For "minimum window" problems, shrink as much as possible before recording the answer.

Common Mistakes

!Shrinking the window too aggressively — only shrink until the window is barely valid, not more.
!Forgetting to update the window state (map/sum) when moving the left pointer.
!Using a nested loop to check validity — this defeats the purpose and makes it O(n²).
!Confusing "at most k distinct" with "exactly k distinct" — the latter needs two sliding windows.
💡 Key Insight:Shrink the left boundary only when the window violates the constraint.

Solved Problems0

No solved problems yet.