Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Sliding Windows over Data Streams

Approximate counts in tiny memory: exponential histograms and DGIM.

A router sees billions of packets and is asked, at any moment, how many of the last million were errors. Storing the last million bits answers exactly, and a short proof shows nothing smaller can. Allow a 10% error and a few hundred buckets of power-of-two sizes, under 4,000 bits, do the job: the exponential histogram of Datar, Gionis, Indyk and Motwani (2002), provably optimal up to constant factors.

What you’ll learn

  • Define the sliding-window streaming model and prove that exact counting of 1s in the last NN bits needs NN bits of memory.
  • Implement an exponential histogram (DGIM) with buckets of power-of-two sizes, merging and expiry, and trace it on a short stream.
  • Prove its relative error bound and its O(ε−1log⁡2N)O(\varepsilon^{-1}\log^2N)-bit memory bound, and state the matching lower bound.
  • Extend the idea to sums, and place it among smooth histograms, sliding-window sampling and streaming sketches.

The sliding-window model

Counting the 1s of the whole stream needs a single counter of O(log⁡t)O(\log t) bits. The window is harder because of expiry: when a 1 drops out of the window, the algorithm must notice, so it must remember when its 1s arrived, not just how many there were. Remembering everything is exact; the surprise is that nothing less is.

DerivationProof
  1. cs(w)=∑i=s+1Nwic_s(w)=\sum_{i=s+1}^{N}w_i

    Write a window as w1…wNw_1\dots w_N, oldest first; every one of the 2N2^N bit strings can occur. If zeros arrive next, after ss of them the window holds the newest N−sN-s bits of ww followed by zeros, so the correct answer is

  2. cs−1(w)−cs−1(w′)=ws−ws′=±1c_{s-1}(w)-c_{s-1}(w')=w_s-w'_s=\pm1

    Take two different windows w≠w′w\ne w', and let ss be the largest index with ws≠ws′w_s\ne w'_s. All later bits agree, so after s−1s-1 zeros the correct answers differ by exactly one:

  3. #states ≥ 2N⟹memory ≥ log⁡22N=N bits\#\text{states}\ \ge\ 2^N\quad\Longrightarrow\quad\text{memory}\ \ge\ \log_2 2^N=N\ \text{bits}

    An algorithm in the same memory state on ww and w′w' would behave identically on the same future input and give the same answers, a contradiction. So the 2N2^N windows need 2N2^N different states:

Exponential histograms

The way out is approximation. An exponential histogram groups the 1s of the window into buckets. A bucket stores two things: its size, a power of two, and the arrival time of its newest 1. Recent 1s sit in small buckets, old ones in large buckets, so the uncertainty is concentrated in the oldest bucket, the only one that can straddle the window's edge. This is the DGIM algorithm, in a simple form with a parameter r≥2r\ge2:

  • A 1 arrives: create a bucket of size 1. Whenever r+1r+1 buckets share a size, merge the two oldest into one of twice the size, stamped with the newer of the two times. Merges can cascade upward like carries.
  • Expiry: drop the oldest bucket once its time leaves the window.
  • Query: add all bucket sizes, then subtract half of the oldest bucket's size, rounded down.
python
from collections import deque

class ExpHistogram:
    """Approximate count of 1s among the last N bits of a stream (a DGIM-style histogram)."""
    def __init__(self, N, r):
        self.N, self.r, self.t = N, r, 0
        self.levels = []                       # levels[i]: times of the buckets of size 2**i, oldest first

    def add(self, bit):
        self.t += 1
        top = len(self.levels) - 1             # the oldest bucket sits in the highest nonempty level
        while top >= 0 and not self.levels[top]:
            top -= 1
        if top >= 0 and self.levels[top][0] <= self.t - self.N:
            self.levels[top].popleft()         # its newest 1 has left the window
        if bit:
            stamp, i = self.t, 0               # a new bucket of size 1
            while stamp is not None:
                if i == len(self.levels):
                    self.levels.append(deque())
                self.levels[i].append(stamp)
                stamp = None
                if len(self.levels[i]) > self.r:     # r + 1 buckets of this size: merge the two oldest
                    self.levels[i].popleft()
                    stamp = self.levels[i].popleft() # the merged bucket keeps the newer time
                    i += 1

    def estimate(self):
        total = oldest = 0
        for i, q in enumerate(self.levels):
            if q:
                total += len(q) << i
                oldest = 1 << i                # size of the oldest bucket (the highest level)
        return total - oldest // 2             # the oldest bucket may stick out of the window

Python integers keep exact times here; a real implementation stores each time modulo NN, which suffices because every stored time lies in the last NN steps.

Bucket sizeTime of its newest 1Its 1s arrived atInside the window
461, 3, 4, 6only the 1 at time 6
4117, 8, 10, 11all 4
21413, 14both
21615, 16both
11818yes
11919yes
N=16N=16, r=2r=2, after the 20 bits 1,0,1,1,0,1,1,1,0,1,1,0,1,1,1,1,0,1,1,01,0,1,1,0,1,1,1,0,1,1,0,1,1,1,1,0,1,1,0. The window holds times 5–20, with 11 ones. The estimate is 4+4+2+2+1+1−⌊4/2⌋=124+4+2+2+1+1-\lfloor4/2\rfloor=12: only the oldest bucket is uncertain, and it contributes 1 of its 4.

Error, memory and optimality

DerivationProof
  1. S+1 ≤ C ≤ S+2jS+1\ \le\ C\ \le\ S+2^j

    Let the oldest bucket have size 2j2^j and let SS be the total size of all the others. Their 1s are newer than the oldest bucket's newest 1, which is inside the window, so they are all inside; of the oldest bucket, between one and all of its 1s are inside:

  2. ∣C^−C∣ ≤ 2j−1\abs{\hat C-C}\ \le\ 2^{j-1}

    The estimate is C^=S+2j−1\hat C=S+2^{j-1} for j≥1j\ge1 (and exact for j=0j=0), the midpoint of that range up to rounding, so

  3. C ≥ S+1 ≥ (r−1) (2j−1)+1 > (r−1) 2j−1(j≥1)C\ \ge\ S+1\ \ge\ (r-1)\,(2^j-1)+1\ >\ (r-1)\,2^{j-1}\qquad(j\ge1)

    A bucket of size 2j2^j exists only because every smaller size has overflowed, and a size keeps r−1r-1 buckets after each of its merges, losing buckets only to further merges (expiry removes the oldest bucket, which has the largest size). So every size 2i2^i with i<ji<j holds at least r−1r-1 buckets:

  4. ∣C^−C∣C < 2j−1(r−1) 2j−1 = 1r−1\frac{\abs{\hat C-C}}{C}\ <\ \frac{2^{j-1}}{(r-1)\,2^{j-1}}\ =\ \frac{1}{r-1}

    Dividing the error by CC gives the accuracy. The same inequality bounds the sizes: since S≤N−1S\le N-1, (r−1)(2j−1)≤N−1(r-1)(2^j-1)\le N-1, so at most log⁡2(N−1r−1+1)+1\log_2(\tfrac{N-1}{r-1}+1)+1 sizes occur, each with at most rr buckets. Each arriving 1 adds one bucket and each merge removes one, so merges never outnumber arrivals.

Predict before you look

For a window of N=106N=10^6 bits and r=11r=11 (error below 10%), what is the bound on the number of buckets, r(⌊log⁡2(N−1r−1+1)⌋+1)r\big(\lfloor\log_2(\tfrac{N-1}{r-1}+1)\rfloor+1\big)?

Show the answer

187

N−1r−1+1≈100,001\tfrac{N-1}{r-1}+1\approx100{,}001 and ⌊log⁡2100,001⌋=16\lfloor\log_2 100{,}001\rfloor=16, so at most 1717 sizes with 1111 buckets each: 187 buckets. With 20-bit times that is 3,740 bits, about 470 bytes, against 10610^6 bits for exact counting. The bound is nearly tight: on a stream of all 1s with N=20,000N=20{,}000 and r=11r=11, a simulation reaches 119 buckets against a bound of 121.

Datar, Gionis, Indyk and Motwani proved a matching lower bound: any algorithm that estimates the count within a factor 1±ε1\pm\varepsilon, deterministic or randomized, needs Ω(ε−1log⁡2N)\Omega(\varepsilon^{-1}\log^2N) bits. So the exponential histogram is optimal up to constant factors; their own accounting of buckets differs from the simple version here only in constants.

Signs break everything. If the stream may contain negative values, say from {−1,0,1}\{-1,0,1\}, they show that even a constant-factor approximation of the window's sum needs Ω(N)\Omega(N) bits: cancellation lets a window of large positive and negative parts sum to almost nothing, and the algorithm cannot know what will expire.

Beyond counting

Sums of non-negative integers. If every item is an integer in [0,R][0,R], write it in binary and run one histogram per bit position: the sum of the window is ∑i2iCi\sum_i2^iC_i, where CiC_i counts the 1s in bit position ii. Using ⌊log⁡2R⌋+1\lfloor\log_2R\rfloor+1 histograms multiplies the memory by O(log⁡R)O(\log R). Datar, Gionis, Indyk and Motwani also give a direct histogram for sums, with matching upper and lower bounds.

Check your understanding

Each per-bit histogram estimates its count CiC_i within relative error ε\varepsilon. Why is the combined estimate ∑i2iC^i\sum_i2^i\hat C_i of the window's sum also within relative error ε\varepsilon?

  1. The errors of different bit positions cancel out on average
  2. Every term is non-negative, so ∣∑i2i(C^i−Ci)∣≤∑i2iεCi=ε∑i2iCi\abs{\sum_i2^i(\hat C_i-C_i)}\le\sum_i2^i\varepsilon C_i=\varepsilon\sum_i2^iC_i
  3. Only the highest bit position matters
  4. It is not: the error grows by a factor equal to the number of bit positions
Show the answer

B. Every term is non-negative, so ∣∑i2i(C^i−Ci)∣≤∑i2iεCi=ε∑i2iCi\abs{\sum_i2^i(\hat C_i-C_i)}\le\sum_i2^i\varepsilon C_i=\varepsilon\sum_i2^iC_i

The triangle inequality bounds the total error by the weighted sum of the individual errors, and each of those is at most ε\varepsilon times a non-negative count. No cancellation is needed, so the guarantee holds deterministically.

Other statistics. Babcock, Datar, Motwani and O'Callaghan (2003) maintained the variance and kk-medians clusterings of a window with histogram-like structures. Braverman and Ostrovsky (2007) introduced smooth histograms, which turn many insertion-only streaming algorithms into sliding-window algorithms for functions that change smoothly as old items are dropped, such as many norms of the window. Random samples of a window, which simple reservoir sampling cannot provide because items expire, need their own techniques too.

Counting distinct items or frequent items in a window combines these ideas with hashing-based sketches; see Count-Min, HyperLogLog & Streaming Sketches.

Key takeaways

  • In the sliding-window model, exact counting of 1s in the last NN bits needs NN bits: feeding zeros distinguishes any two windows.
  • An exponential histogram keeps at most rr buckets of each power-of-two size, merges the two oldest on overflow, expires the oldest, and counts half of the oldest bucket.
  • Its relative error is below 1/(r−1)1/(r-1), its memory O(ε−1log⁡2N)O(\varepsilon^{-1}\log^2N) bits, and DGIM's matching lower bound makes it optimal up to constants; with negative values even approximation needs Ω(N)\Omega(N) bits.
  • Sums of bounded non-negative integers, variance, clustering and smooth functions extend the idea; frequent and distinct items combine it with hashing sketches.

Check yourself

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

Question 1

Why must an exact counter of 1s in the last NN bits remember about NN bits?

  1. Because the count itself can be as large as NN
  2. Because any two different windows can be told apart by feeding zeros and watching the exact counts, so they need different memory states
  3. Because the algorithm must be able to output the window itself
  4. It need not: a counter of log⁡2N\log_2 N bits plus the time of the oldest 1 suffices
Show the answer

B. Because any two different windows can be told apart by feeding zeros and watching the exact counts, so they need different memory states

Feed zeros until the last bit where the two windows differ is about to expire: the exact counts then differ by one. Same state would force the same answers, so the 2N2^N windows need 2N2^N states.

Question 2

Why does the estimate subtract half of the oldest bucket's size?

  1. Because the oldest bucket always has exactly half of its 1s inside the window
  2. Because merging doubled its size by mistake
  3. Because anywhere from one to all of its 1s are inside the window, and half splits the difference
  4. To make the estimate always smaller than the true count
Show the answer

C. Because anywhere from one to all of its 1s are inside the window, and half splits the difference

Every other bucket lies entirely inside the window; the oldest one is known to have its newest 1 inside, but not how many of the rest. Counting half of it keeps the error at most half its size, and the r−1r-1 buckets of each smaller size make that small relative to the count.

Question 3

The histogram uses O(ε−1log⁡2N)O(\varepsilon^{-1}\log^2 N) bits. Where does each factor log⁡N\log N come from?

  1. One from the number of bucket sizes, one from the bits needed to store each bucket's time
  2. One from sorting the buckets, one from binary search
  3. Both from the cascade of merges
  4. One from the counter, one from the sizes written in binary
Show the answer

A. One from the number of bucket sizes, one from the bits needed to store each bucket's time

Sizes are powers of two up to about NεN\varepsilon, so there are O(log⁡N)O(\log N) of them, each with O(1/ε)O(1/\varepsilon) buckets; every bucket stores a time modulo NN, O(log⁡N)O(\log N) bits. DGIM showed this product cannot be beaten by more than a constant.

Question 4

A stream contains values −1-1, 00 and +1+1, and you want the sum of the last NN values within a constant factor. What is true?

  1. One histogram for the +1+1s and one for the −1-1s, subtracted, gives relative error ε\varepsilon
  2. The bit-decomposition trick handles it in O(ε−1log⁡2N)O(\varepsilon^{-1}\log^2N) bits
  3. An exponential histogram works unchanged
  4. Every algorithm needs Ω(N)\Omega(N) bits: cancellation can make the true sum tiny while the window is full of information
Show the answer

D. Every algorithm needs Ω(N)\Omega(N) bits: cancellation can make the true sum tiny while the window is full of information

DGIM proved this lower bound. Subtracting two good estimates fails because the difference of two large, nearly equal numbers can be tiny, so their small relative errors become a huge relative error of the difference.

Further reading

  • M. Datar, A. Gionis, P. Indyk & R. Motwani, "Maintaining stream statistics over sliding windows," SIAM Journal on Computing 31(6) (2002), 1794–1813; extended abstract at SODA 2002.
  • B. Babcock, M. Datar, R. Motwani & L. O'Callaghan, "Maintaining variance and k-medians over data stream windows," PODS 2003.
  • V. Braverman & R. Ostrovsky, "Smooth histograms for sliding windows," FOCS 2007.
  • J. Leskovec, A. Rajaraman & J. D. Ullman, Mining of Massive Datasets, 3rd ed. (Cambridge University Press, 2020), chapter 4, "Mining data streams".
  • G. Cormode & K. Yi, Small Summaries for Big Data (Cambridge University Press, 2020).