Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Sliding-Window Aggregation

Windows for min, gcd and other operations you cannot subtract.

A running sum slides in O(1)O(1) per step because subtraction undoes addition. Minimum, gcd and matrix products have no such undo, and recomputing each window costs O(k)O(k). Two stacks fix that for every associative operation, at about three operations per element on average; production stream processors go further and guarantee O(1)O(1) in the worst case.

What you’ll learn

  • Define sliding-window aggregation for an associative operation, and say which operations a running aggregate handles directly.
  • Implement the two-stack window aggregator, prove its order invariant, and show that it uses O(1)O(1) operations per element amortized.
  • Choose among the monotonic deque, the block method, sparse tables and segment trees by operation, latency and whether the data is static.
  • Explain how de-amortization gives worst-case O(1)O(1) aggregation (DABA), and what remains open for streams.

What subtraction buys

If ⊕\oplus has inverses, a running aggregate is enough: combine the newcomer in, combine the leaver's inverse out, O(1)O(1) per step in the worst case. Otherwise the naive method recombines the whole window for every query, Θ(k)\Theta(k) each and Θ(nk)\Theta(nk) in all.

OperationInverse?Commutative?Idempotent (x⊕x=xx\oplus x=x)?
Sum, XORyesyesno
Minimum, maximumnoyesyes
gcd, bitwise AND / ORnoyesyes
2×22\times2 matrix product (e.g. composing linear maps)not alwaysnono
String concatenation, function compositionnonono
Associativity is all the general methods below need. Idempotence enables sparse tables, and selection (the result is one of the operands, as for min and max) enables the monotonic deque.
Check your understanding

For which operation can a sliding window be maintained with O(1)O(1) worst-case work per step, using just one running aggregate?

  1. gcd
  2. Maximum
  3. Bitwise OR
  4. XOR
Show the answer

D. XOR

XOR is its own inverse: XOR the newcomer in and XOR the leaver out, since x⊕x=0x\oplus x=0. The other three forget information: knowing gcd⁡(12,18)=6\gcd(12,18)=6 does not tell you the gcd after 12 leaves.

Two stacks with running aggregates

A FIFO queue can be built from two stacks (see Stacks, Queues & Deques): push onto a back stack, pop from a front stack, and when the front is empty, move everything over, which reverses the order. Add aggregates: each front entry stores the aggregate from itself to the newest element of the front, and the back keeps one running aggregate. The window's aggregate is then one ⊕\oplus away.

python
class SlidingAggregate:
    """FIFO window reporting op(oldest, ..., newest) for any associative op; no inverse needed."""
    def __init__(self, op):
        self.op = op
        self.front = []                    # (value, op of this value .. newest value in front)
        self.back = []                     # the newer values, oldest at the bottom
        self.back_agg = None               # op of all values in back, in order

    def push(self, x):                     # x enters as the newest value
        self.back.append(x)
        self.back_agg = x if self.back_agg is None else self.op(self.back_agg, x)

    def pop(self):                         # the oldest value leaves
        if not self.front:                 # flip: move back to front, newest first
            agg = None
            while self.back:
                x = self.back.pop()
                agg = x if agg is None else self.op(x, agg)   # x is older: it goes left
                self.front.append((x, agg))
            self.back_agg = None
        self.front.pop()

    def query(self):                       # op over the whole window, or None if it is empty
        if not self.front:
            return self.back_agg
        if self.back_agg is None:
            return self.front[-1][1]
        return self.op(self.front[-1][1], self.back_agg)

Tested against direct recomputation with gcd, min, string concatenation and 2×22\times2 matrix products: the last two are not commutative, so the order of the operands matters.

DerivationInvariant and amortized cost
  1. query=agg(front)⏟top entry⊕agg(back)⏟back_agg\text{query}=\underbrace{\mathrm{agg}(\text{front})}_{\text{top entry}}\oplus\underbrace{\mathrm{agg}(\text{back})}_{\texttt{back\_agg}}

    Order invariant. The window, oldest first, is the front stack read from top to bottom followed by the back stack read from bottom to top. Each front entry stores its own value combined with every front value below it, in window order, and back_agg combines the back stack in order. Hence

  2. agg(xi,…,xj)=xi⊕agg(xi+1,…,xj)\mathrm{agg}(x_i,\dots,x_j)=x_i\oplus\mathrm{agg}(x_{i+1},\dots,x_j)

    The flip keeps it. Values leave the back newest first, and each one is older than everything already moved, so it is combined on the left: agg←x⊕agg\mathrm{agg}\leftarrow x\oplus\mathrm{agg}. With a non-commutative ⊕\oplus, writing agg⊕x\mathrm{agg}\oplus x here would be a bug.

  3. #⊕ ≤ 2n+q\#\oplus\ \le\ 2n+q

    Cost. Every element is combined at most once when pushed and once when moved by a flip, and never again; every query costs one ⊕\oplus. So nn insertions, any evictions and qq queries cost

  4. worst single eviction=Θ(k)\text{worst single eviction}=\Theta(k)

    That is O(1)O(1) amortized per operation: give each pushed element two credits, one for its push and one for its single move. A single eviction can still cost Θ(k)\Theta(k), when it triggers a flip of the whole window.

Measured on 10410^4 random elements with windows of k=100k=100 and one query per window: about 2.95 applications of ⊕\oplus per element. With gcd⁡\gcd as the operation, the gcd of every window of length 3 in [12,18,24,9,15,10,20,30][12,18,24,9,15,10,20,30] is 6,3,3,1,5,106,3,3,1,5,10. Because "gcd >1>1" is hereditary (a sub-window's gcd is a multiple of the window's), the same aggregator also drives a variable window:

python
from math import gcd

def longest_gcd_above_one(a):
    W, L, best = SlidingAggregate(gcd), 0, 0
    for R, x in enumerate(a):
        W.push(x)
        while W.query() == 1:              # "gcd > 1" is hereditary: shrink until it holds
            W.pop()
            L += 1
        best = max(best, R - L + 1)
    return best

print(longest_gcd_above_one([12, 18, 24, 9, 15, 10, 20, 30]))   # 5: [12, 18, 24, 9, 15]

O(n)O(n) applications of gcd, each O(log⁡V)O(\log V) for values up to VV, where recomputing every window would cost O(n2)O(n^2) of them.

Special cases: deques, blocks and tables

For minimum and maximum a lighter structure suffices. In a sliding maximum, an element that is older than some larger (or equal) element can never be the answer again: it will leave the window first. A monotonic deque keeps only the candidates that are not dominated, so their values decrease from front to back; each index is pushed once and popped at most once, O(1)O(1) amortized per step. The trick needs a selection operation, one whose result is one of its operands, so it does not extend to gcd or sums.

When the window length kk is fixed and the array is stored, there is a branch-free alternative for any associative operation, the block method of van Herk (1992) and of Gil and Werman (1993), first used for image filters. Cut the array into blocks of length kk and compute, inside each block, running aggregates from its start (prefix) and toward its end (suffix). A window of length kk either is a block or straddles two neighbors, so it is one suffix combined with one prefix:

python
def window_aggregates(a, k, op):
    """op over every window a[i..i+k-1], with about 3n op calls: blocks of length k."""
    n = len(a)
    prefix, suffix = a[:], a[:]            # inside each block: from its start / to its end
    for i in range(1, n):
        if i % k:                          # not the first element of a block
            prefix[i] = op(prefix[i - 1], a[i])
    for i in range(n - 2, -1, -1):
        if (i + 1) % k:                    # not the last element of a block
            suffix[i] = op(a[i], suffix[i + 1])
    return [suffix[i] if i % k == 0 else op(suffix[i], prefix[i + k - 1])
            for i in range(n - k + 1)]

print(window_aggregates([12, 18, 24, 9, 15, 10, 20, 30], 3, gcd))   # [6, 3, 3, 1, 5, 10]

Worst-case O(1)O(1) per window and about 3n3n applications of ⊕\oplus in total (2.96 per element measured with k=100k=100), but each answer needs elements up to kk positions ahead: a latency of one block, acceptable for stored data, not for answering at every arrival.

MethodOperationsCost per stepSetting
Running aggregateinvertible (sum, XOR)O(1)O(1) worst caseonline
Two stacksany associativeO(1)O(1) amortized, Θ(k)\Theta(k) worstonline, any window sizes
Monotonic dequemin, maxO(1)O(1) amortizedonline
Blocks (van Herk; Gil & Werman)any associativeO(1)O(1) worst per windowfixed kk, latency kk
Sparse tableidempotent (min, max, gcd, AND, OR)O(1)O(1) per query after O(nlog⁡n)O(n\log n)static array, any ranges
Segment treeany associativeO(log⁡n)O(\log n) per query or updatedynamic array, any ranges
DABA (next step)any associativeO(1)O(1) worst caseonline
Pick by the operation's algebra first, then by whether you need answers online, for fixed or varying windows, and with worst-case guarantees.

Worst-case O(1), and the streaming frontier

In a stream processor that must emit an aggregate after every event, an amortized bound is not enough: the occasional Θ(k)\Theta(k) flip is a latency spike. The cure is de-amortization, the idea behind Okasaki's real-time queues and global rebuilding: start the expensive reorganization early and advance it by a constant number of steps during each ordinary operation, so that it is finished by the time it is needed.

DABA, the De-Amortized Banker's Aggregator of Tangwongsan, Hirzel and Schneider (2017), applies this to the two-stack idea. It keeps the window in a single deque with a few internal boundaries, and every insert, evict and query performs O(1)O(1) applications of ⊕\oplus in the worst case, for any associative operation, in O(k)O(k) space. The same group later extended worst-case-efficient aggregation to out-of-order streams, where an event may arrive late and must be inserted dd positions from the end, at a cost that grows only logarithmically in dd.

Think first A sensor network sends one reading per millisecond, and a dashboard must show the gcd of the last 60,000 readings after every arrival, never pausing. Which method fits, and why not the others?

A worst-case O(1)O(1) aggregator such as DABA. The two-stack method is O(1)O(1) only amortized: once per 60,000 evictions it flips the whole window, a visible pause. A monotonic deque cannot do gcd. The block method has a latency of one window, and a sparse table needs a static array. A running gcd cannot evict, because gcd has no inverse.

Key takeaways

  • Sliding-window aggregation needs only associativity: invertible operations keep one running aggregate, and everything else needs more structure.
  • Two stacks with stored aggregates answer every query with one ⊕\oplus and use at most 2n+q2n+q applications in total: O(1)O(1) amortized, Θ(k)\Theta(k) for an unlucky single eviction.
  • Special structure buys more: the monotonic deque for min and max, blocks for fixed windows over stored data, sparse tables for idempotent operations on static arrays, segment trees for dynamic ones.
  • De-amortization (DABA) makes every operation O(1)O(1) in the worst case, which latency-bound stream processors need.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

The two-stack aggregator processes nn insertions, nn evictions and qq queries. How many applications of ⊕\oplus does it make at most?

  1. n⋅kn\cdot k
  2. O(nlog⁡n)O(n\log n)
  3. 2n+q2n+q
  4. 2n+q2n+q on random inputs, but Θ(nk)\Theta(nk) on adversarial sequences of operations
Show the answer

C. 2n+q2n+q

Each element is combined once on insertion and once when a flip moves it; evictions themselves combine nothing, and each query combines the two stack aggregates once. Individual flips are expensive, but each element is flipped at most once.

Question 2

Why can a monotonic deque maintain sliding maxima but not sliding gcds?

  1. gcd is not associative
  2. For the maximum, an older element that is at most a newer one can never matter again; gcd has no such domination, since every element can still change the result
  3. A deque cannot store more than kk elements
  4. gcd is too slow to compute inside a deque
Show the answer

B. For the maximum, an older element that is at most a newer one can never matter again; gcd has no such domination, since every element can still change the result

The deque discards dominated candidates, which is valid because the maximum of a window is one of its elements and a larger, newer element outlives an older one. The gcd of a window is generally not one of its elements, and removing any element can change it.

Question 3

During a flip, the aggregator computes agg = op(x, agg) rather than op(agg, x). Why?

  1. It saves one application of op
  2. Values leave the back stack newest first, so each xx is older than everything already combined, and op need not be commutative
  3. Python evaluates the left operand first
  4. Either order works, because op is associative
Show the answer

B. Values leave the back stack newest first, so each xx is older than everything already combined, and op need not be commutative

The front's aggregates must follow window order, oldest first. With matrix products or string concatenation, op(agg, x) would combine the window in the wrong order and return a wrong answer; with min or gcd both orders happen to agree.

Question 4

The block method computes every window of a fixed length kk with about 3 applications of ⊕\oplus per element, in the worst case. What does it require that the two-stack window does not?

  1. An invertible operation
  2. A commutative operation
  3. A fixed window length and access to elements up to kk positions ahead
  4. O(nlog⁡n)O(n\log n) preprocessing
Show the answer

C. A fixed window length and access to elements up to kk positions ahead

Each window combines a suffix of one block with a prefix of the next, so the block structure fixes kk, and the prefix of the next block is known only once its elements have arrived. That suits stored arrays and image filters, not answers after every arrival.

Further reading

  • K. Tangwongsan, M. Hirzel & S. Schneider, "Low-latency sliding-window aggregation in worst-case constant time," Proceedings of the ACM Conference on Distributed and Event-Based Systems (DEBS 2017).
  • C. Okasaki, Purely Functional Data Structures (Cambridge University Press, 1998): real-time queues and de-amortization.
  • M. van Herk, "A fast algorithm for local minimum and maximum filters on rectangular and octagonal kernels," Pattern Recognition Letters (1992).
  • J. Gil & M. Werman, "Computing 2-D min, median, and max filters," IEEE Transactions on Pattern Analysis and Machine Intelligence (1993).
  • A. Laaksonen, Competitive Programmer's Handbook (2018, free online), §8.3 "Sliding window minimum".