AS
Back to Learn
Unit III · Searching

Sliding Window

· Step 3/7 · Drill
Drill
Step 3 of 7

Slide the window — reuse the sum

A window slides over a sequence so you re-use work instead of recomputing — turning O(n²) brute force into O(n).

The challenge

Given an array and window size k, return the maximum sum of any contiguous window — without recomputing.

Example
max_window_sum([2, 1, 5, 1, 3, 2], k=3) → 9
You will need to know
  • Arrays are contiguous in memory — indexing is O(1).
  • A *window* is a contiguous sub-range `[l..r]`. Fixed-size windows have constant width k.
  • Sum of a slice can be maintained incrementally: when the window shifts right by one, subtract `nums[l]` and add `nums[r+1]`.
  • Maintaining a running aggregate turns an O(n·k) brute force into O(n).
window
incremental update
two pointers

Next, your AI tutor will guide you through it — Socratic style.