Practice Discrete Math

Algorithms / Monotonic Deque Prefix Sum

Least You Need to Know: Monotonic Deques, Prefix Sums, and Shortest Valid Windows

Some subarray problems use prefix sums plus a monotonic deque over prefix indices. The deque keeps promising earlier prefixes in increasing order so the current prefix can quickly detect the shortest earlier start that already makes the sum large enough.

The least you need to know

Key notation

P[i] prefix sum of the first i elements
P[j] - P[i] sum of the subarray from i to j-1
dominated prefix an earlier prefix with a larger sum than a later candidate

Tiny worked example

  • Build prefix sums `P[0], P[1], ..., P[n]`.
  • Maintain deque indices whose prefix sums are increasing.
  • At each new prefix `P[j]`, pop from the front while `P[j] - P[front]` already meets the target, recording shorter lengths.
  • Pop from the back while `P[j]` is smaller than the back prefix, because the back is dominated.

Common mistakes

How to recognize this kind of problem

Start practice