Two-Stack Sliding-Window Aggregation

An aggregation is some kind of summary of a set of data. This can be the sum, length, minimum, etc. It is quite common to want to calculate such a summary repeatedly, e.g. “the maximum noise level in dB for the past 30 seconds” for a nuisance detector. In such a case we say there is a sliding window over our data, and we want to aggregate over our window.

If our aggregation is a binary operator with an inverse, like integer sums, there is a very easy solution using a double-ended queue:

from collections import deque

class SlidingWindowSum: def init(self): self.sum = 0 self.elems = deque()

def push(self, x):
    self.sum += x
    self.elems.append(x)

def pop(self):
    self.sum -= self.elems.popleft()

def eval(self):
    return self.sum