Back to Data Structures and Algorithms

Sliding Window Complete Guide

Algorithm • medium

Sliding window maintains a moving contiguous range while updating state incrementally.

It is the go-to strategy for substring/subarray constraints where you need best/min/max window under rules.

The key is deterministic add-right/remove-left updates so each index is touched a constant number of times.

Typical Complexity Baseline

MetricValue
Typical traversalO(n)

See It

Concept Diagram

A small animated SVG that illustrates the core idea the moving parts you need to keep in your head when you read the rest of the guide.

Sliding window fixed-width scan

The window slides one step at a time, adding the new element and dropping the old one.

window size k = 3 · update sum in O(1) per slide41372581window sum = 8best so far = 8
Step 1/6Initial window [0..2] sum = 8.

Watch First

Video Explainer

A quick visual walkthrough before the detailed sections pick the format that helps you learn fastest.

Mechanics

Core Concepts

The building blocks and terminology you need before everything else clicks. Skim or deep-read.

Window boundaries

What it is Left and right pointers defining active range.

Why it matters Window boundaries is a required building block for understanding how Sliding Window stays correct and performant on large inputs.

Add step

What it is Include right element and update state.

Why it matters Add step is a required building block for understanding how Sliding Window stays correct and performant on large inputs.

Shrink step

What it is Move left boundary until constraints restore.

Why it matters Shrink step is a required building block for understanding how Sliding Window stays correct and performant on large inputs.

State tracker

What it is Counts/sums/sets needed for validity checks.

Why it matters State tracker is a required building block for understanding how Sliding Window stays correct and performant on large inputs.

Best answer update

What it is Capture optimal window length/value when valid.

Why it matters Best answer update is a required building block for understanding how Sliding Window stays correct and performant on large inputs.

Fixed window

What it is Window size is constant (e.g., length k).

Why it matters Window size is constant (e.g., length k). In Sliding Window, this definition helps you reason about correctness and complexity when inputs scale.

Variable window

What it is Window expands/shrinks based on validity condition.

Why it matters Window expands/shrinks based on validity condition. In Sliding Window, this definition helps you reason about correctness and complexity when inputs scale.

Window validity

What it is Constraint currently satisfied for active range.

Why it matters Constraint currently satisfied for active range. In Sliding Window, this definition helps you reason about correctness and complexity when inputs scale.

Amortized linear

What it is Each index enters/leaves window at most once.

Why it matters Each index enters/leaves window at most once. In Sliding Window, this definition helps you reason about correctness and complexity when inputs scale.

Frequency map

What it is Character/value counts used to evaluate window constraints.

Why it matters Character/value counts used to evaluate window constraints. In Sliding Window, this definition helps you reason about correctness and complexity when inputs scale.

Walkthrough

Putting It All Together

Every frame of the concept diagram, laid out top-to-bottom so you can scroll through the algorithm at your own pace.

Step 1/6
window size k = 3 · update sum in O(1) per slide41372581window sum = 8best so far = 8

Initial window [0..2] sum = 8.

Step 2/6
window size k = 3 · update sum in O(1) per slide41372581window sum = 11best so far = 11

Slide right. drop 4, add 7. window sum = 11. best = 11.

Step 3/6
window size k = 3 · update sum in O(1) per slide41372581window sum = 12best so far = 12

Slide right. drop 1, add 2. window sum = 12. best = 12.

Step 4/6
window size k = 3 · update sum in O(1) per slide41372581window sum = 14best so far = 14

Slide right. drop 3, add 5. window sum = 14. best = 14.

Step 5/6
window size k = 3 · update sum in O(1) per slide41372581window sum = 15best so far = 15

Slide right. drop 7, add 8. window sum = 15. best = 15.

Step 6/6
window size k = 3 · update sum in O(1) per slide41372581window sum = 14best so far = 15

Slide right. drop 2, add 1. window sum = 14. best = 15.

Tradeoffs

How It Compares

When this technique wins, when it loses, and what to reach for instead.

vs. Prefix sums

Choose this when Choose sliding window when constraints depend on mutable content inside range.

Tradeoff Prefix sums are better for static sum queries.

vs. Two pointers

Choose this when Choose sliding window for contiguous range optimization.

Tradeoff General two pointers may be simpler for pairwise non-window problems.

vs. Brute-force subarray scan

Choose this when Choose sliding window to avoid O(n^2) range enumeration.

Tradeoff Needs careful state update design.

In Production

Real-World Stories

Where this shows up at real companies and what the on-call engineer learned the hard way.

Datadog

Monitoring alerts evaluate rolling windows over metrics streams to detect spikes and anomalies.

Takeaway Sliding windows are practical for continuous observability workloads.

Cloudflare

Rate-limiting systems apply per-key request windows to enforce fair usage.

Takeaway Window-based constraints protect services under burst traffic.

Spotify

Session analytics often rely on rolling windows for engagement and retention signals.

Takeaway Window logic underpins many product analytics metrics.

Code

Implementation

A clean reference implementation in TypeScript, Python, and Go. Switch languages with the toggle.

Use a manual fixed-size last-seen table so the window updates are explicit without built-in map classes.

Complexity: Time O(n), Space O(min(n, alphabet))

Longest unique substring with variable window

function longestUniqueWindow(text: string): number {
  const lastSeenIndexes = new Array<number>(256).fill(-1)
  let leftIndex = 0
  let bestLength = 0

  for (let rightIndex = 0; rightIndex < text.length; rightIndex += 1) {
    const charCode = text.charCodeAt(rightIndex) & 255
    const seenIndex = lastSeenIndexes[charCode]

    if (seenIndex >= leftIndex) {
      leftIndex = seenIndex + 1
    }

    lastSeenIndexes[charCode] = rightIndex
    const currentWindowLength = rightIndex - leftIndex + 1
    if (currentWindowLength > bestLength) {
      bestLength = currentWindowLength
    }
  }

  return bestLength
}

Watch Out

Common Problems and Failure Modes

The bugs and edge cases that bite engineers most often. Skim before you ship.

  • Not shrinking enough when window invalidates.
  • Updating answer before ensuring validity.
  • Incorrectly handling repeated characters/items.
  • Mixing fixed and variable window logic.
  • Not clearing state between test cases in reusable helpers.

Pro Tips

Tips and Tricks

Small habits that pay off every time you reach for this pattern.

  • Sliding window shines for contiguous subarray/substring optimization tasks.
  • Maintain incremental state; never recompute full window from scratch.
  • Shrink window only while constraint is violated, then resume expansion.
  • Use frequency maps and distinct counters together for tight complexity bounds.

Pattern Recognition

When to Use

Concrete signals that tell you this is the right pattern both at work and on LeetCode.

Real-system usage signals

  • Transforms repeated subarray recomputation into linear-time updates.
  • Natural fit for real-time stream monitoring and threshold checks.
  • Works well with hash maps and frequency counters for text/data windows.

LeetCode-specific tips (pattern-identification signals)

  • Identification signal: prompt asks for longest/shortest contiguous segment meeting a constraint.
  • Identification signal: recomputing each window from scratch is too slow, but add/remove updates are possible.
  • Words like "at most k", "contains all", or "without repeating" often map directly to sliding-window templates.
  • For Sliding Window questions, start by naming the core invariant before writing code.
  • Use the constraint section to set time/space target first, then pick the data structure/algorithm.
  • Solve one tiny example by hand and map each transition to your variables before implementing.
  • Run adversarial cases: empty input, duplicates, max-size input, and sorted/reverse patterns when relevant.
  • During interviews, explain why your approach is the right pattern for this prompt, not just why the code works.

Practice

LeetCode Progression

A curated easy-to-hard problem ladder. Each one reinforces a specific aspect of the pattern.