TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › Sublinear Estimation: Averages and Connected Components

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 μ\mu of nn numbers in [0,1][0, 1] within ±ε\pm \varepsilon, sample ss of them uniformly with replacement and average. By Hoeffding's inequality, the sample mean deviates by more than ε\varepsilon with probability at most 2e−2sε22e^{-2s\varepsilon^2}, so

s=⌈ln⁡(2/δ)2ε2⌉s = \Bigl\lceil \frac{\ln(2/\delta)}{2\varepsilon^2} \Bigr\rceil

samples suffice, independent of nn. Two remarks shape everything that follows. The error is additive: for a relative error (1±ε)μ(1 \pm \varepsilon)\mu one needs about 1ε2μ\frac{1}{\varepsilon^2 \mu} samples, which is large when μ\mu is small. And the values must be bounded: if one value in nn is huge, a sample of size o(n)o(n) misses it, and no sampling scheme can estimate the mean within a constant factor.

The average degree of a graph

The average degree dˉ=2m/n\bar d = 2m/n 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 O(n/dˉ/ε)O(\sqrt{n/\bar d}/\varepsilon) queries give a (2+ε)(2 + \varepsilon)-approximation, and that a factor below 2 needs Ω(n)\Omega(n) degree queries. With neighbour queries ("the jj-th neighbour of vv"), Goldreich and Ron (2008) reach (1+ε)(1 + \varepsilon) with O~(n/dˉ)poly⁡(1/ε)\tilde O(\sqrt{n/\bar d})\operatorname{poly}(1/\varepsilon) 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 m=∑vout⁡(v)m = \sum_v \operatorname{out}(v). Pick a uniform vertex vv and a uniform neighbour uu, and output X=2deg⁡(v)X = 2\deg(v) if the edge v→uv \to u is oriented away from vv, else 0. Then

E[X]=1n∑vdeg⁡(v)⋅2out⁡(v)deg⁡(v)=2mn=dˉ,\mathbb{E}[X] = \frac{1}{n}\sum_v \deg(v)\cdot\frac{2\operatorname{out}(v)}{\deg(v)} = \frac{2m}{n} = \bar d ,

and since every out-degree is at most 2m\sqrt{2m} (a vertex with out-degree kk has kk neighbours of degree at least kk, so k2≤2mk^2 \le 2m), the variance is controlled, which gives O(n/dˉ/ε2)O(\sqrt{n/\bar d}/\varepsilon^2) samples. The program compares it with the naive mean of sampled degrees on a random graph and on a graph with a hub.

python · try it yourself
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 cc be the number of connected components of a graph with nn vertices and maximum degree dd, and C(v)C(v) the component of vv. Each component of size kk has kk vertices that each contribute 1k\frac{1}{k}, so

c=∑v1∣C(v)∣=n⋅Ev[1∣C(v)∣].c = \sum_{v} \frac{1}{\lvert C(v) \rvert} = n \cdot \mathbb{E}_v\Bigl[\frac{1}{\lvert C(v) \rvert}\Bigr] .

1∣C(v)∣\frac{1}{\lvert C(v) \rvert} is in [0,1][0, 1], so sampling works, but computing ∣C(v)∣\lvert C(v) \rvert may need a BFS over a huge component. Truncation fixes it: run the BFS only until it has found W=⌈2/ε⌉W = \lceil 2/\varepsilon \rceil vertices, and use 1min⁡(∣C(v)∣,W)\frac{1}{\min(\lvert C(v) \rvert, W)}. That changes the value only for vertices in components larger than WW, by at most 1W≤ε2\frac{1}{W} \le \frac{\varepsilon}{2} each, so the truncated sum differs from cc by at most ε2n\frac{\varepsilon}{2} n.

text
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 εn\varepsilon n of cc with probability at least 23\frac{2}{3}. Each BFS makes O(Wd)=O(d/ε)O(Wd) = O(d/\varepsilon) queries, so the total is O(d/ε3)O(d/\varepsilon^3), independent of nn; a refined version (random stopping sizes) brings it to O~(d/ε2)\tilde O(d/\varepsilon^2).

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 ε=0.1\varepsilon = 0.1.

python · try it yourself
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 εn\varepsilon n. The giant component is responsible for a small upward bias: its vertices count as 120\frac{1}{20} each instead of 130 000\frac{1}{30\,000}, adding about 0.005n0.005n.

In C++

The same estimator with compressed adjacency lists on a graph with two million vertices and ε=0.05\varepsilon = 0.05: about 1600 truncated searches, a few tens of thousands of queries.

cpp · try it yourself
#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 {1,…,w}\{1, \ldots, w\} and cic_i is the number of components of the subgraph of edges of weight at most ii (with c0=nc_0 = n), Kruskal's algorithm shows

MST⁡(G)=n−w+∑i=1w−1ci.\operatorname{MST}(G) = n - w + \sum_{i=1}^{w-1} c_i .

Estimating each cic_i within εwn\frac{\varepsilon}{w} n gives the MST weight within a factor 1+ε1 + \varepsilon (the MST weighs at least n−1n - 1), in time O~(dw/ε2)\tilde O(d w / \varepsilon^2)-type bounds, independent of nn. 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 c=∑v1/∣C(v)∣c = \sum_v 1/\lvert C(v) \rvert the number of connected components?

  1. By Euler's formula
  2. Each component of size kk contributes kk terms of 1/k1/k, which add up to 1
  3. Because every vertex is in one component
  4. By linearity of expectation

Why does truncating the BFS at W=2/εW = 2/\varepsilon vertices cost at most εn/2\varepsilon n/2 in the estimate?

  1. Because large components are rare
  2. Because it changes 1/∣C(v)∣1/\lvert C(v) \rvert only for vertices in components larger than WW, each by at most 1/W=ε/21/W = \varepsilon/2
  3. Because BFS is exact
  4. Because dd is bounded

Why does the naive average of sampled degrees fail on a graph with one hub joined to all vertices?

  1. The hub's degree is not queryable
  2. 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)
  3. The graph is disconnected
  4. Sampling with replacement is biased