Sublinear Estimation: Averages and Connected Components
Testers answer yes/no questions. Many sublinear-time algorithms instead estimate a number: an average, the average degree of a graph, the number of connected components, the weight of a minimum spanning tree. The common pattern is to write the quantity as an average over vertices of something that can be computed locally, by looking only at a small neighbourhood, and then to sample. Two difficulties recur: the local quantity may be expensive to compute exactly (then truncate it), and its distribution may be heavy-tailed (then reweight it). This lesson shows both, ending with the algorithm of Chazelle, Rubinfeld and Trevisan (2005) that counts connected components in time independent of the number of vertices.
Averages of bounded values
To estimate the mean of numbers in within , sample of them uniformly with replacement and average. By Hoeffding's inequality, the sample mean deviates by more than with probability at most , so
samples suffice, independent of . Two remarks shape everything that follows. The error is additive: for a relative error one needs about samples, which is large when is small. And the values must be bounded: if one value in is huge, a sample of size misses it, and no sampling scheme can estimate the mean within a constant factor.
The average degree of a graph
The average degree is the average of the degrees, but degrees are unbounded: a star has average degree almost 2, while all but one vertex have degree 1. With degree queries only, Feige (2006) showed that queries give a -approximation, and that a factor below 2 needs degree queries. With neighbour queries ("the -th neighbour of "), Goldreich and Ron (2008) reach with queries.
A particularly simple unbiased estimator (Eden, Ron and Seshadhri, 2017) orients every edge from the endpoint of lower degree to the one of higher degree (ties broken by name), so that . Pick a uniform vertex and a uniform neighbour , and output if the edge is oriented away from , else 0. Then
and since every out-degree is at most (a vertex with out-degree has neighbours of degree at least , so ), the variance is controlled, which gives samples. The program compares it with the naive mean of sampled degrees on a random graph and on a graph with a hub.
import random
def naive(adj, s, rng):
"""Average of the degrees of s random vertices."""
return sum(len(adj[rng.randrange(len(adj))]) for _ in range(s)) / s
def oriented(adj, s, rng):
"""Random vertex v, random neighbour u; count 2 deg(v) if the edge points 'up' from v (by degree, then id)."""
total = 0
for _ in range(s):
v = rng.randrange(len(adj))
if adj[v]:
u = rng.choice(adj[v])
if (len(adj[v]), v) < (len(adj[u]), u):
total += 2 * len(adj[v])
return total / s
rng = random.Random(2017)
n = 20000
rand = [[] for _ in range(n)]
for _ in range(5 * n): # random graph with average degree 10
u, v = rng.randrange(n), rng.randrange(n)
if u != v:
rand[u].append(v); rand[v].append(u)
star = [[] for _ in range(n)]
for v in range(1, n): # a hub joined to everyone, plus a sparse random part
star[0].append(v); star[v].append(0)
for _ in range(n // 2):
u, v = rng.randrange(1, n), rng.randrange(1, n)
if u != v:
star[u].append(v); star[v].append(u)
for name, adj in [("random, average degree 10", rand), ("hub + sparse random", star)]:
true = sum(len(a) for a in adj) / n
nv = [naive(adj, 400, rng) for _ in range(5)]
ov = [oriented(adj, 400, rng) for _ in range(5)]
print(f"{name}: true average degree {true:.2f}")
print(" naive sample mean of degrees:", " ".join(f"{x:5.2f}" for x in nv))
print(" oriented-edge estimator: ", " ".join(f"{x:5.2f}" for x in ov))random, average degree 10: true average degree 10.00
naive sample mean of degrees: 10.11 10.11 9.75 9.93 10.30
oriented-edge estimator: 9.15 9.72 9.80 10.23 9.49
hub + sparse random: true average degree 3.00
naive sample mean of degrees: 2.08 2.00 2.04 2.07 51.99
oriented-edge estimator: 3.00 2.91 2.92 3.00 2.99
On the random graph both work. With a hub, the naive mean sees only the leaves and reports about 2 instead of 3, except in the one run where it happened to sample the hub and reported 52. The oriented estimator charges each hub edge to its leaf end, where samples do find it, and is right every time.
Counting connected components
Let be the number of connected components of a graph with vertices and maximum degree , and the component of . Each component of size has vertices that each contribute , so
is in , so sampling works, but computing may need a BFS over a huge component. Truncation fixes it: run the BFS only until it has found vertices, and use . That changes the value only for vertices in components larger than , by at most each, so the truncated sum differs from by at most .
Component counting (Chazelle, Rubinfeld and Trevisan, 2005), simplified
1 W ← ⌈2/ε⌉; s ← O(1/ε²)
2 repeat s times: pick a random vertex v; BFS from v, stopping after W vertices; record 1/(vertices found)
3 return n · (average of the recorded values)Theorem (Chazelle, Rubinfeld and Trevisan, 2005). The estimate is within of with probability at least . Each BFS makes queries, so the total is , independent of ; a refined version (random stopping sizes) brings it to .
The program builds graphs of increasing size, each with one giant tree on a tenth of the vertices and many small random trees, and runs the estimator with .
import math, random
from collections import deque
def make_graph(n, rng):
"""One giant random tree on a tenth of the vertices, the rest in small random trees."""
adj = [[] for _ in range(n)]
order = list(range(n))
rng.shuffle(order)
i = 0
while i < n:
size = n // 10 if i == 0 else min(n - i, rng.choice([1, 2, 3, 5, 8, 13]))
comp = order[i:i + size]
for j in range(1, size):
u, v = comp[j], comp[rng.randrange(j)] # attach to an earlier vertex: a random tree
adj[u].append(v); adj[v].append(u)
i += size
return adj
def capped_component_size(adj, s, cap):
"""BFS from s, stopping once cap vertices are found; returns (min(size, cap), queries)."""
seen, queue, queries = {s}, deque([s]), 0
while queue and len(seen) < cap:
u = queue.popleft()
for v in adj[u]:
queries += 1
if v not in seen:
seen.add(v); queue.append(v)
if len(seen) >= cap:
break
return len(seen), queries
def estimate_components(adj, eps, rng):
"""Chazelle-Rubinfeld-Trevisan: c = sum_v 1/|C(v)|; sample vertices, cap sizes at 2/eps."""
n, cap = len(adj), math.ceil(2 / eps)
samples = math.ceil(4 / eps ** 2)
total, queries = 0.0, 0
for _ in range(samples):
size, q = capped_component_size(adj, rng.randrange(n), cap)
total += 1 / size
queries += q
return n * total / samples, queries
def exact_components(adj):
n, seen, c = len(adj), [False] * len(adj), 0
for s in range(n):
if not seen[s]:
c += 1
seen[s] = True
stack = [s]
while stack:
for v in adj[stack.pop()]:
if not seen[v]:
seen[v] = True; stack.append(v)
return c
rng = random.Random(2005)
eps = 0.1
for n in [10000, 100000, 300000]:
adj = make_graph(n, rng)
c = exact_components(adj)
est, q = estimate_components(adj, eps, rng)
print(f"n = {n}: components {c}, estimate {est:.0f}, error {abs(est - c) / n:.4f} n "
f"(target eps = {eps}), {q} adjacency queries")n = 10000: components 1662, estimate 1673, error 0.0011 n (target eps = 0.1), 6641 adjacency queries
n = 100000: components 16865, estimate 19082, error 0.0222 n (target eps = 0.1), 6070 adjacency queries
n = 300000: components 50766, estimate 51772, error 0.0034 n (target eps = 0.1), 6472 adjacency queries
The number of queries stays near 6 000 while the graph grows thirty-fold, and the error stays well below . The giant component is responsible for a small upward bias: its vertices count as each instead of , adding about .
In C++
The same estimator with compressed adjacency lists on a graph with two million vertices and : about 1600 truncated searches, a few tens of thousands of queries.
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <numeric>
#include <random>
#include <unordered_set>
#include <utility>
#include <vector>
struct Graph { // compressed adjacency lists
std::vector<std::uint32_t> start, nbr;
std::uint32_t n() const { return (std::uint32_t)start.size() - 1; }
};
Graph build(std::uint32_t n, const std::vector<std::pair<std::uint32_t, std::uint32_t>>& edges) {
Graph g;
g.start.assign(n + 1, 0);
for (auto [u, v] : edges) { ++g.start[u + 1]; ++g.start[v + 1]; }
for (std::uint32_t i = 0; i < n; ++i) g.start[i + 1] += g.start[i];
g.nbr.resize(g.start[n]);
std::vector<std::uint32_t> pos(g.start.begin(), g.start.end() - 1);
for (auto [u, v] : edges) { g.nbr[pos[u]++] = v; g.nbr[pos[v]++] = u; }
return g;
}
// Chazelle-Rubinfeld-Trevisan: n * mean of 1 / min(|C(v)|, cap) over random vertices v.
double estimate_components(const Graph& g, double eps, std::mt19937_64& rng, long& queries) {
const std::size_t cap = (std::size_t)std::ceil(2 / eps), samples = (std::size_t)std::ceil(4 / (eps * eps));
double total = 0;
for (std::size_t t = 0; t < samples; ++t) {
std::uint32_t s = rng() % g.n();
std::unordered_set<std::uint32_t> seen{s};
std::vector<std::uint32_t> queue{s};
for (std::size_t head = 0; head < queue.size() && seen.size() < cap; ++head)
for (std::uint32_t k = g.start[queue[head]]; k < g.start[queue[head] + 1] && seen.size() < cap; ++k) {
++queries;
if (seen.insert(g.nbr[k]).second) queue.push_back(g.nbr[k]);
}
total += 1.0 / seen.size();
}
return g.n() * total / samples;
}
int main() {
const std::uint32_t n = 2000000;
std::mt19937_64 rng(2005);
std::vector<std::uint32_t> perm(n);
std::iota(perm.begin(), perm.end(), 0u);
for (std::uint32_t i = n - 1; i > 0; --i) std::swap(perm[i], perm[rng() % (i + 1)]);
std::vector<std::pair<std::uint32_t, std::uint32_t>> edges;
std::uint32_t comps = 0;
const std::uint32_t sizes[] = {1, 2, 3, 5, 8, 13};
for (std::uint32_t i = 0; i < n; ++comps) { // random trees of small sizes
std::uint32_t size = std::min<std::uint32_t>(n - i, sizes[rng() % 6]);
for (std::uint32_t j = 1; j < size; ++j) edges.push_back({perm[i + j], perm[i + rng() % j]});
i += size;
}
Graph g = build(n, edges);
long queries = 0;
double est = estimate_components(g, 0.05, rng, queries);
std::printf("n = %u vertices, %u components; estimate %.0f (error %.4f n), %ld adjacency queries\n",
n, comps, est, std::fabs(est - comps) / n, queries);
}n = 2000000 vertices, 375186 components; estimate 367829 (error 0.0037 n), 24080 adjacency queries
The weight of a minimum spanning tree
Chazelle, Rubinfeld and Trevisan used component counting to approximate the weight of a minimum spanning tree in sublinear time. If the edge weights are integers in and is the number of components of the subgraph of edges of weight at most (with ), Kruskal's algorithm shows
Estimating each within gives the MST weight within a factor (the MST weighs at least ), in time -type bounds, independent of . The general lesson: local quantities, averaged by sampling, give global estimates, a theme continued by local computation algorithms, which answer queries about one part of a global solution (one edge of a maximal matching, say) by exploring a small neighbourhood.
Test yourself
Why is the number of connected components?
- By Euler's formula
- Each component of size contributes terms of , which add up to 1
- Because every vertex is in one component
- By linearity of expectation
Why does truncating the BFS at vertices cost at most in the estimate?
- Because large components are rare
- Because it changes only for vertices in components larger than , each by at most
- Because BFS is exact
- Because is bounded
Why does the naive average of sampled degrees fail on a graph with one hub joined to all vertices?
- The hub's degree is not queryable
- Degrees are unbounded: the hub holds half of the edge endpoints but is almost never sampled, so the estimate is about half the truth (or wildly too large when the hub is hit)
- The graph is disconnected
- Sampling with replacement is biased