The Two-Stack Trick That Solves Sliding-Window Aggregation for Almost Any Function

Two-Stack Sliding-Window Aggregation

Sliding-window aggregation is easy when your operation has an inverse, like integer sums. But for min, max, quantiles, or even floating-point sums, the naive approach fails—a single NaN can poison your results forever. This post explains the two-stack algorithm, a simple, amortized O(1) method that works for any associative aggregation. It also shows how the algorithm avoids error propagation from outliers, making it ideal for floating-point windows.

Each aggregate is strictly a combination of the elements in the window, and none outside the window. This means if your window contains a NaN or infinity (or some other outlier), that value only poisons the windows that contain it rather than the rest of your computation.
  1. mlochbaum

    As you suspected, there's some older literature on this, from the 1990s in image processing. There it's not based on stacks or queues but on splitting the output into blocks with the same size as the (constant-length) window. It's sometimes called the van Herk/Gil-Werman algorithm after two sets of independent discoverers; of the two papers I prefer "Computing 2-D Min, Median, and Max Filters" by Gil and Werman which spends just a paragraph on the 1-D windowed operation in section II.

    I don't know who first described this as a streaming version but I like the presentation at https://signalsmith-audio.co.uk/writing/2022/constant-time-p... . It is indeed too obscure considering how useful it is!

  2. tinco

    Very cool, might I suggest you rename your `pop` function to `shift` (or if you like ugly names `popleft`)? Popping windows isn't really a thing, it made me double take on the code.

  3. bradrn

    I just want to comment that, quite aside from the content (which is very interesting) I particularly enjoy the design of this website — it’s very clean and balanced and easy to read. (In fact I first encountered it a while ago, noted this at the time, then forgot the URL. I’m glad to have come across it again.)

More from this day

2026-10-16