view_sidebar

Sliding Window
Curriculum

A structured path to mastering the sliding window pattern. Track contiguous subarrays with dynamic boundaries and state.

What This Pattern Is Really About

open_in_fullDynamic Boundaries

Window expands to explore new elements and contracts when constraints are violated. Boundaries move independently based on validity.

analyticsState Tracking

Maintain window properties incrementally—sum, frequency, distinct count. Update state as elements enter and exit the window.

ruleValidity Condition

Window is either valid (satisfies constraint) or being adjusted. Expand when valid, contract when invalid. Binary state drives movement.

speedSingle Pass

Each element enters the window once and exits once. O(n) time guaranteed—no nested loops, no backtracking.

Mental Model & Invariant

Sliding window is a moving frame over contiguous elements.

"At any moment, the window either satisfies the constraint or is being adjusted to satisfy it. All elements outside the window have been processed and cannot improve the current solution."

The Core Invariant
The window maintains a valid or adjusting state. Every optimal subarray either lies within current boundaries or has already been recorded.

Break this, and you miss valid solutions or examine invalid regions.

verified

When It Holds

Before expansion, after contraction, and at every boundary update. If violated, your window logic is incorrect.

gavel

Movement Rule

Expand right to explore. Contract left when invalid. State updates must reflect boundary changes immediately.

flag

Termination

When right pointer reaches the end, all possible windows have been examined. Either optimal solution found or none exists.

When to Think "Sliding Window"

sensorsStrong Signals

draw

Contiguous subarray or substring

draw

Longest/shortest with constraint

draw

At most K distinct elements

draw

Maximum/minimum sum of size K

draw

All subarrays satisfying property

draw

Running state can be tracked incrementally

ruleConstraint Signals

lock_clock

Must solve in linear time

lock_clock

Cannot use nested loops

lock_clock

State updates are O(1)

lock_clock

Boundaries move monotonically

Variants You Must Master

width_normal

Fixed-Size Window

Window size is constant. Slide by removing left and adding right.

// Invariant
Window always contains exactly K elements.
Max sum KAvg subarrayFixed length
unfold_more

Variable-Size Window

Expand until invalid, then contract until valid again.

// Invariant
Window is valid or being adjusted.
Longest substringAt most KMin window
compare_arrows

Two-Pointer Variant

Left and right move independently based on validity.

// Invariant
All valid windows examined or recorded.
Subarray sumProduct < KDistinct chars
stacked_line_chart

Monotonic Window

Maintain monotonic property within window using deque.

// Invariant
Deque tracks min/max candidates.
Max in windowMin in windowSliding extrema

How to Learn This Pattern

1

Define Window Validity

Write down what makes a window valid. What constraint must hold? What state tracks this?

2

Identify State Updates

How does state change when element enters? When element exits? Must be O(1) operations.

3

Determine Movement Logic

When do you expand? When do you contract? What triggers each boundary movement?

4

Trace Fixed-Size First

Start with fixed window size K. Slide by removing left, adding right. Verify state updates.

5

Progress to Variable-Size

Expand while valid, contract while invalid. Track optimal window during traversal.

6

Verify Edge Cases

Empty input, single element, all invalid, all valid. Confirm invariant holds throughout.

Canonical Problem List

auto_awesome_motion

Fixed Window

Window size K is constant. Slide by removing i-K and adding i.

unfold_more

Variable Window

Expand right until invalid; then contract left until valid again.

stacked_line_chart

Monotonic Window

Maintain max/min candidate in deque. Remove useless elements.

Common Mistakes

error_outline

Not Updating State Correctly

Failure Mode

Window state becomes stale; validity checks fail; wrong answers returned.

Mastery Fix

Update state immediately when element enters or exits. Verify state reflects current window.

error_outline

Incorrect Shrinking Logic

Failure Mode

Window contracts too early or too late; misses optimal solutions or examines invalid regions.

Mastery Fix

Contract only when invalid. Use while loop for contraction, not if statement.

error_outline

Off-by-One in Window Boundaries

Failure Mode

Window size calculation wrong; includes or excludes wrong elements.

Mastery Fix

Window size is (right - left + 1). Verify with small examples.

error_outline

Forgetting to Track Optimal

Failure Mode

Find valid windows but don't record the best one; return wrong answer.

Mastery Fix

Update optimal solution whenever valid window found. Track max/min explicitly.

error_outline

Confusing Fixed vs Variable Window

Failure Mode

Use wrong expansion/contraction logic; algorithm doesn't match problem type.

Mastery Fix

Fixed: slide by +1 each step. Variable: expand until invalid, then contract.

Interview Guidance

Interview Protocol

What they test

  • Window Validity Definition
  • State Management Precision
  • Boundary Movement Justification

Strategy

Avoid "I'll use sliding window" without context. Instead: "I need to track contiguous elements with a constraint, so I'll maintain a window that expands when valid and contracts when invalid."

The Verbal Template

Validity

"A window is valid when [constraint holds]. I track this using [state]."

Expansion

"I expand right to include new elements and update state by [operation]."

Contraction

"When invalid, I contract left until valid again, updating state by [operation]."

Optimal

"I track the best window seen so far and update when [condition]."

When You've Mastered It

done_all

Immediate window type recognition

done_all

State defined before coding

done_all

Validity condition articulated clearly

done_all

Boundary logic justified precisely

done_all

Edge cases handled analytically

done_all

Flawless state update implementation

What This Unlocks Next

stacked_line_chart

Monotonic Stack/Deque

Extends window concept with monotonic property tracking for extrema.

account_tree

Dynamic Programming

Sliding window optimizes DP state transitions for contiguous subproblems.

compare_arrows

Two Pointers

Generalizes to non-contiguous element pairing and partitioning.

network_check

Streaming Algorithms

Real-world application in rate limiting, buffering, and time-series analysis.