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 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 , 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
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 counters on the same 12-item stream as the Misra-Gries animation, breaking ties between equal counts by the item's name.
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 is 1, the truth.
The guarantees
Lemma 1. The counters always sum to the number of items read so far, .
Proof. Lines 3 and 4 add 1 to the total; line 7 removes and adds .
Lemma 2. Once items are stored, the smallest count satisfies .
Proof. counts sum to (Lemma 1), so the smallest is at most the average.
Theorem (Metwally, Agrawal and El Abbadi, 2005). For every stored item , , and . Every item with , in particular every item with , is stored.
Proof. Consider the moment last entered the summary, taking over a count , so . Before that moment, had occurred at most times: each earlier occurrence was counted in some counter of 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 added 1 to . So and . An item that is not stored has by the same argument applied to its last eviction, so items with are stored.
So Space-Saving has the mirror image of the Misra-Gries guarantee: estimates are never below the truth and at most above it. Its estimates are often better in practice, because the error bound is known per item and is usually much smaller than for items that entered early.
Top- queries. If the items sorted by estimate are and the guaranteed count of , , is at least for every , then the first items are certainly the true top in order. Metwally et al. use this to report top- answers together with a certificate.
Space-Saving is Misra-Gries
Theorem (Agarwal, Cormode, Huang, Phillips, Wei and Yi, 2012). Run Space-Saving with counters and Misra-Gries with counters on the same stream. Then for every item , the Misra-Gries estimate equals , where is the smallest Space-Saving count (0 while fewer than 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 by a newcomer with , 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 and the mergeability of Misra-Gries (Mergeable Summaries). The program checks the equivalence on a Zipf stream, together with Lemma 2 and the theorem.
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 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 or . The original paper uses a stream-summary structure of buckets of equal counts in a doubly linked list, which gives . The version below uses std::set of (count, item) pairs ordered by count, with per update, which is simpler and fast enough for most uses.
#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 ; 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 ( counters) | Space-Saving ( counters) | |
|---|---|---|
| error direction | underestimates by at most | overestimates by at most |
| per-item certificate | no (only the global ) | yes, |
| update | increment, insert, or decrement all ( amortized) | increment or replace the minimum ( 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 ?
- Because they are reset periodically
- Because every step adds exactly 1 to the total: an increment, a new counter of 1, or a replacement of count by
- Because divides
- Because evicted items are remembered
What does the stored error certify in Space-Saving?
- Nothing; it is a heuristic
How do Space-Saving with counters and Misra-Gries with counters relate?
- They are unrelated
- The Misra-Gries estimate equals the Space-Saving estimate minus the smallest Space-Saving count (floored at 0), for every item
- Space-Saving is always exact on the top item
- Misra-Gries uses more space