TExcelTAD

Space-Saving

Misra-Gries underestimates: an item's counter loses occurrences in decrement steps. Space-Saving (Metwally, Agrawal and El Abbadi, 2005) takes the opposite approach. It never decrements. When a new item arrives and all kk counters are taken, it evicts the item with the smallest count and gives the newcomer that count plus one, on the pessimistic assumption that the newcomer might have occurred that often before. The result overestimates instead, by at most m/km/k, and comes with a per-item error bound that often certifies the answer. In practice it is the most accurate of the counter-based summaries, and it turns out to be Misra-Gries in disguise.

The algorithm

text
Space-Saving with k counters
1  C ← empty map item → count;  err ← empty map item → error bound
2  for each item x:
3      if x ∈ C: C[x] ← C[x] + 1
4      else if |C| < k: C[x] ← 1; err[x] ← 0
5      else:
6          y ← an item of C with the smallest count; c ← C[y]
7          remove y;  C[x] ← c + 1;  err[x] ← c
8  estimate of f_x: C[x] if x ∈ C, else the smallest count (or 0 if fewer than k items are stored)

The program runs it with k=3k = 3 counters on the same 12-item stream as the Misra-Gries animation, breaking ties between equal counts by the item's name.

python · try it yourself
from collections import Counter

def space_saving(stream, k, trace=False):
    C, err = {}, {}
    for t, x in enumerate(stream, 1):
        if x in C:
            C[x] += 1
            what = "monitored, +1"
        elif len(C) < k:
            C[x], err[x] = 1, 0
            what = "free counter"
        else:
            y = min(C, key=lambda z: (C[z], z))     # smallest count, ties by name
            c = C.pop(y)
            err.pop(y)
            C[x], err[x] = c + 1, c                  # x takes over y's counter
            what = f"evict {y} (count {c}), {x} starts at {c + 1}"
        if trace:
            print(f"{t:2} {x}: " + " ".join(f"{a}={C[a]}" for a in sorted(C)) + f"   {what}")
    return C, err

stream = "a b a c a d b a e b a b".split()
C, err = space_saving(stream, 3, trace=True)
true = Counter(stream)
print("item  true  estimate  error   (estimate - error <= true <= estimate)")
for x in sorted(C):
    print(f"{x:>4}  {true[x]:4}  {C[x]:8}  {err[x]:5}")
 1 a: a=1   free counter
 2 b: a=1 b=1   free counter
 3 a: a=2 b=1   monitored, +1
 4 c: a=2 b=1 c=1   free counter
 5 a: a=3 b=1 c=1   monitored, +1
 6 d: a=3 c=1 d=2   evict b (count 1), d starts at 2
 7 b: a=3 b=2 d=2   evict c (count 1), b starts at 2
 8 a: a=4 b=2 d=2   monitored, +1
 9 e: a=4 d=2 e=3   evict b (count 2), e starts at 3
10 b: a=4 b=3 e=3   evict d (count 2), b starts at 3
11 a: a=5 b=3 e=3   monitored, +1
12 b: a=5 b=4 e=3   monitored, +1
item  true  estimate  error   (estimate - error <= true <= estimate)
   a     5         5      0
   b     4         4      2
   e     1         3      2

Item a is exact and certified exact (error 0). Item e occurred once but is reported as 3: it took over a counter of value 2. Its error bound says so, and the guaranteed count C[x]−err[x]C[x] - \text{err}[x] is 1, the truth.

The guarantees

Lemma 1. The counters always sum to the number of items read so far, mm.

Proof. Lines 3 and 4 add 1 to the total; line 7 removes cc and adds c+1c + 1. □\square

Lemma 2. Once kk items are stored, the smallest count cmin⁡c_{\min} satisfies cmin⁡≤m/kc_{\min} \le m/k.

Proof. kk counts sum to mm (Lemma 1), so the smallest is at most the average. □\square

Theorem (Metwally, Agrawal and El Abbadi, 2005). For every stored item xx, C[x]−err[x]≤fx≤C[x]C[x] - \text{err}[x] \le f_x \le C[x], and err[x]≤cmin⁡≤m/k\text{err}[x] \le c_{\min} \le m/k. Every item with fx>cmin⁡f_x > c_{\min}, in particular every item with fx>m/kf_x > m/k, is stored.

Proof. Consider the moment xx last entered the summary, taking over a count cc, so err[x]=c\text{err}[x] = c. Before that moment, xx had occurred at most cc times: each earlier occurrence was counted in some counter of xx that was later evicted at a value at most the current minimum, and minima never decrease (counts only grow, and a replacement starts above the old minimum). Since then every occurrence of xx added 1 to C[x]C[x]. So fx≤c+(C[x]−c−1)+1=C[x]f_x \le c + (C[x] - c - 1) + 1 = C[x] and fx≥C[x]−cf_x \ge C[x] - c. An item that is not stored has fx≤cmin⁡f_x \le c_{\min} by the same argument applied to its last eviction, so items with fx>cmin⁡f_x > c_{\min} are stored. □\square

So Space-Saving has the mirror image of the Misra-Gries guarantee: estimates are never below the truth and at most m/km/k above it. Its estimates are often better in practice, because the error bound err[x]\text{err}[x] is known per item and is usually much smaller than m/km/k for items that entered early.

Top-kk queries. If the items sorted by estimate are x1,x2,…x_1, x_2, \ldots and the guaranteed count of xjx_j, C[xj]−err[xj]C[x_j] - \text{err}[x_j], is at least C[xj+1]C[x_{j+1}] for every j<rj < r, then the first rr items are certainly the true top rr in order. Metwally et al. use this to report top-kk answers together with a certificate.

Space-Saving is Misra-Gries

Theorem (Agarwal, Cormode, Huang, Phillips, Wei and Yi, 2012). Run Space-Saving with kk counters and Misra-Gries with k−1k - 1 counters on the same stream. Then for every item xx, the Misra-Gries estimate equals max⁡(f^xSS−cmin⁡,0)\max(\hat f^{\text{SS}}_x - c_{\min}, 0), where cmin⁡c_{\min} is the smallest Space-Saving count (0 while fewer than kk items are stored).

The idea: subtracting the minimum from all Space-Saving counters is exactly the bulk decrement of Misra-Gries. When Space-Saving replaces an item with count cmin⁡c_{\min} by a newcomer with cmin⁡+1c_{\min} + 1, the minimum either stays or increases by 1; Misra-Gries correspondingly either just stores the newcomer or performs a decrement step. The full proof is an induction over the stream with some care about ties; it is stated here. Two consequences: Space-Saving inherits the tighter bound fx−f^xMG≤(m−m′)/kf_x - \hat f^{\text{MG}}_x \le (m - m')/k and the mergeability of Misra-Gries (Mergeable Summaries). The program checks the equivalence on a Zipf stream, together with Lemma 2 and the theorem.

python · try it yourself
import random
from collections import Counter

def space_saving(stream, k):
    C, err = {}, {}
    for x in stream:
        if x in C:
            C[x] += 1
        elif len(C) < k:
            C[x], err[x] = 1, 0
        else:
            y = min(C, key=lambda z: (C[z], z))
            c = C.pop(y)
            err.pop(y)
            C[x], err[x] = c + 1, c
    return C, err

def misra_gries(stream, k):
    C = {}
    for x in stream:
        if x in C:
            C[x] += 1
        elif len(C) < k - 1:
            C[x] = 1
        else:
            for y in list(C):
                C[y] -= 1
                if C[y] == 0:
                    del C[y]
    return C

rng = random.Random(2005)
U = 20000
cum, s = [], 0.0
for i in range(U):
    s += 1 / (i + 1) ** 1.1
    cum.append(s)
stream = rng.choices(range(U), cum_weights=cum, k=50000)
true = Counter(stream)
m = len(stream)
for k in [20, 100]:
    SS, err = space_saving(stream, k)
    MG = misra_gries(stream, k)
    mn = min(SS.values()) if len(SS) == k else 0
    equiv = all(max(SS.get(x, 0) - mn, 0) == MG.get(x, 0) for x in true)
    over = max(SS[x] - true[x] for x in SS)
    certain = sorted(x for x in SS if SS[x] - err[x] > m / k)
    print(f"k = {k}: counters sum to {sum(SS.values())} = m; min counter {mn} <= m/k = {m / k:.0f}; "
          f"largest overestimate {over}")
    print(f"   Misra-Gries (k-1 counters) == max(SS - min, 0) for every item: {equiv}")
    print(f"   certified f > m/k (count - error > m/k): {certain}")
    print(f"   truly f > m/k:                           {sorted(x for x in true if true[x] > m / k)}")
k = 20: counters sum to 50000 = m; min counter 2183 <= m/k = 2500; largest overestimate 2183
   Misra-Gries (k-1 counters) == max(SS - min, 0) for every item: True
   certified f > m/k (count - error > m/k): [0, 1]
   truly f > m/k:                           [0, 1]
k = 100: counters sum to 50000 = m; min counter 331 <= m/k = 500; largest overestimate 331
   Misra-Gries (k-1 counters) == max(SS - min, 0) for every item: True
   certified f > m/k (count - error > m/k): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
   truly f > m/k:                           [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

The certificates found every item above m/km/k without a second pass, and the equivalence holds for every item of the universe.

In C++

An efficient implementation needs "find the minimum" and "increment a count" in O(1)O(1) or O(log⁡k)O(\log k). The original paper uses a stream-summary structure of buckets of equal counts in a doubly linked list, which gives O(1)O(1). The version below uses std::set of (count, item) pairs ordered by count, with O(log⁡k)O(\log k) per update, which is simpler and fast enough for most uses.

cpp · try it yourself
#include <bit>
#include <cstdint>
#include <cstdio>
#include <random>
#include <set>
#include <unordered_map>
#include <utility>

class SpaceSaving {
    std::size_t k;
    std::unordered_map<std::uint64_t, std::pair<std::uint64_t, std::uint64_t>> C;   // item -> (count, error)
    std::set<std::pair<std::uint64_t, std::uint64_t>> byCount;                         // (count, item)
public:
    explicit SpaceSaving(std::size_t k) : k(k) {}
    void add(std::uint64_t x) {
        if (auto it = C.find(x); it != C.end()) {
            byCount.erase({it->second.first, x});
            byCount.insert({++it->second.first, x});
        } else if (C.size() < k) {
            C[x] = {1, 0};
            byCount.insert({1, x});
        } else {
            auto [c, y] = *byCount.begin();                 // smallest count (ties: smallest id)
            byCount.erase(byCount.begin());
            C.erase(y);
            C[x] = {c + 1, c};
            byCount.insert({c + 1, x});
        }
    }
    std::pair<std::uint64_t, std::uint64_t> get(std::uint64_t x) const {
        auto it = C.find(x);
        return it == C.end() ? std::pair<std::uint64_t, std::uint64_t>{0, 0} : it->second;
    }
};

int main() {
    std::mt19937_64 rng(2005);
    const std::uint64_t m = 1000000, k = 50;
    SpaceSaving ss(k);
    std::unordered_map<std::uint64_t, std::uint64_t> exact;
    for (std::uint64_t t = 0; t < m; ++t) {
        std::uint64_t r = rng();
        std::uint64_t x = (r & 1) ? std::countr_zero(r >> 1) : (r >> 8) % 100000;
        ss.add(x);
        ++exact[x];
    }
    std::printf("m = %llu, k = %llu, m/k = %llu\n", (unsigned long long)m, (unsigned long long)k,
        (unsigned long long)(m / k));
    std::printf("item      true  estimate  error  certified lower bound\n");
    for (std::uint64_t x = 0; x < 6; ++x) {
        auto [c, e] = ss.get(x);
        std::printf("%4llu  %8llu  %8llu  %5llu  %21llu\n", (unsigned long long)x,
            (unsigned long long)exact[x], (unsigned long long)c, (unsigned long long)e,
            (unsigned long long)(c - e));
    }
}
m = 1000000, k = 50, m/k = 20000
item      true  estimate  error  certified lower bound
   0    250057    250057      0                 250057
   1    124434    124434      0                 124434
   2     62623     62623      0                  62623
   3     30999     30999      0                  30999
   4     15527     15527      0                  15527
   5      7781     11476  11474                      2

The five heaviest items entered early and were never evicted, so their error bound is 0 and their counts are certified exact. Item 5 lies below m/km/k; it was evicted and re-entered, its estimate is off by about 3700, and its error bound (11 474) says honestly that little is known about it.

Misra-Gries or Space-Saving?

Misra-Gries (k−1k - 1 counters) Space-Saving (kk counters)
error direction underestimates by at most m/km/k overestimates by at most m/km/k
per-item certificate no (only the global (m−m′)/k(m - m')/k) yes, err[x]\text{err}[x]
update increment, insert, or decrement all (O(1)O(1) amortized) increment or replace the minimum (O(1)O(1) with stream-summary)
mergeable yes yes, through the equivalence
deletions no no

Both are deterministic and optimal up to constants for insertion-only streams. Neither tolerates deletions: for turnstile streams the count-min and Count-Sketch linear sketches take over, at the price of randomization.

Test yourself

Why do the Space-Saving counters always sum to exactly mm?

  1. Because they are reset periodically
  2. Because every step adds exactly 1 to the total: an increment, a new counter of 1, or a replacement of count cc by c+1c + 1
  3. Because kk divides mm
  4. Because evicted items are remembered

What does the stored error err[x]\text{err}[x] certify in Space-Saving?

  1. fx=C[x]f_x = C[x]
  2. C[x]−err[x]≤fx≤C[x]C[x] - \text{err}[x] \le f_x \le C[x]
  3. fx≤err[x]f_x \le \text{err}[x]
  4. Nothing; it is a heuristic

How do Space-Saving with kk counters and Misra-Gries with k−1k - 1 counters relate?

  1. They are unrelated
  2. The Misra-Gries estimate equals the Space-Saving estimate minus the smallest Space-Saving count (floored at 0), for every item
  3. Space-Saving is always exact on the top item
  4. Misra-Gries uses more space