TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › The Semi-Streaming Model

The Semi-Streaming Model

A graph with nn vertices can arrive as a stream of its edges: the links of a web crawl, the calls in a phone network, the friendships of a social network as they are recorded. Graph problems in streams behave differently from the frequency problems of the previous sections. Most interesting questions, even "is the graph connected?", need Ω(n)\Omega(n) bits of memory, so polylogarithmic space is out of reach. Feigenbaum, Kannan, McGregor, Suri and Zhang (2005) proposed the semi-streaming model: memory O(npolylog⁡n)O(n \operatorname{polylog} n) bits, enough to store a few things per vertex but not per edge. For dense graphs, with m≫nm \gg n edges, that is still far less than the input. This lesson presents the model and its classical insertion-only algorithms; the next lessons handle deletions and the approximation of cuts.

The model

The stream lists the edges e1,e2,…,eme_1, e_2, \ldots, e_m of a graph on the vertex set [n][n], in arbitrary (adversarial) order, each once. In the dynamic model, edges can also be deleted. The algorithm has O(npolylog⁡n)O(n \operatorname{polylog} n) bits, usually one pass, sometimes a few.

Why nn and not less: connectivity needs Ω(n)\Omega(n) bits in one pass, even for randomized algorithms (Feigenbaum et al., 2005, and Sun and Woodruff, 2015, for the tight Ω(nlog⁡n)\Omega(n \log n)). The idea of the reduction from INDEX (Space Lower Bounds): Alice encodes her bit string as which edges of a fixed structure are present, and Bob adds edges that make the graph connected exactly when Alice's bit xix_i is set. So any algorithm for connectivity is a protocol for INDEX.

Connectivity and spanning forests

Union-find solves connectivity in one pass with O(n)O(n) words: keep the partition of the vertices into components seen so far, and merge two components when an edge joins them.

text
Spanning forest in one pass (insertion-only)
1  UF ← union-find over the n vertices; F ← empty edge list
2  for each edge (u, v) in the stream:
3      if find(u) ≠ find(v): union(u, v); append (u, v) to F
4  F is a spanning forest; the components of UF are the connected components

The forest has at most n−1n - 1 edges, so storing it is also within the budget, and it answers more than connectivity: any two vertices are connected in GG exactly when they are connected in FF. The animation runs union-find (union by rank, path compression) on an 8-edge stream; the program prints which edges are kept.

python · try it yourself
class UnionFind:
    """Union by rank (ties: the first argument's root stays on top) and full path compression."""
    def __init__(self, nodes):
        self.parent = {v: v for v in nodes}
        self.rank = {v: 0 for v in nodes}
    def find(self, x):
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[x] != root:                 # path compression
            self.parent[x], x = root, self.parent[x]
        return root
    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.rank[rb] > self.rank[ra]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        if self.rank[ra] == self.rank[rb]:
            self.rank[ra] += 1
        return True

nodes = "ABCDEFGH"
stream = ["A-B", "C-D", "A-C", "E-F", "B-D", "G-H", "F-H", "E-G"]
uf = UnionFind(nodes)
forest = []
for e in stream:
    u, v = e.split("-")
    if uf.union(u, v):
        forest.append(e)
        print(f"edge {e}: joins two components   -> keep as a forest edge")
    else:
        print(f"edge {e}: both ends already connected -> drop (it closes a cycle)")
print("parents:", " ".join(f"{v}->{uf.parent[v]}" for v in nodes))   # the forest of the last frame
print("spanning forest:", forest)
roots = {v: uf.find(v) for v in nodes}
print("components:", sorted({"".join(sorted(v for v in nodes if roots[v] == r)) for r in roots.values()}))
edge A-B: joins two components   -> keep as a forest edge
edge C-D: joins two components   -> keep as a forest edge
edge A-C: joins two components   -> keep as a forest edge
edge E-F: joins two components   -> keep as a forest edge
edge B-D: both ends already connected -> drop (it closes a cycle)
edge G-H: joins two components   -> keep as a forest edge
edge F-H: joins two components   -> keep as a forest edge
edge E-G: both ends already connected -> drop (it closes a cycle)
parents: A->A B->A C->A D->A E->E F->E G->E H->G
spanning forest: ['A-B', 'C-D', 'A-C', 'E-F', 'G-H', 'F-H']
components: ['ABCD', 'EFGH']

The two dropped edges each closed a cycle, so they carry no connectivity information. The forest is what the algorithm "remembers" of the graph, and it is exactly what the union-find lessons of Part I make fast: O(α(n))O(\alpha(n)) amortized per edge.

More problems in one pass

The same idea extends in several directions.

  • Bipartiteness. Store with each vertex its parity (colour) relative to its parent in the union-find tree. An edge inside one component closes an odd cycle exactly when its two ends have the same colour. O(n)O(n) words, one pass.
  • Minimum spanning forest (weighted edges): keep a spanning forest FF; when an edge closes a cycle in F∪{e}F \cup \{e\}, delete the heaviest edge of that cycle (the cycle property of MSTs). The forest stays a minimum spanning forest of the edges seen. O(n)O(n) words; O(n)O(n) time per edge with a plain forest, faster with link-cut trees.
  • Matching. Keeping an edge whenever both its ends are still free gives a maximal matching, which has at least half as many edges as a maximum matching (every edge of an optimal matching touches an edge of the greedy one). Surprisingly, nothing much better is known in one pass: no one-pass semi-streaming algorithm can beat 1−1e≈0.631 - \frac{1}{e} \approx 0.63 (Kapralov, 2013), and whether 12\frac{1}{2} can be beaten at all is a well-known open problem. With several passes, (1−ε)(1 - \varepsilon)-approximations exist.
  • Spanners and distances. Keep an edge only if its endpoints are currently more than 2k−12k - 1 apart in the kept graph: the result is a (2k−1)(2k-1)-spanner with O(n1+1/k)O(n^{1 + 1/k}) edges, which approximates every distance within a factor 2k−12k - 1 (Althöfer et al., 1993, in the offline setting; the streaming version is the same greedy rule, with a slow update).

The program checks bipartiteness with the parity union-find on a 3000-edge stream between even and odd vertices, then adds one edge between two even vertices; and it compares one-pass greedy matching with a maximum matching.

python · try it yourself
import random

class ParityUnionFind:
    """Union-find that also stores each node's parity (colour) relative to its parent."""
    def __init__(self, n):
        self.parent, self.rank, self.par = list(range(n)), [0] * n, [0] * n
    def find(self, x):
        path = []
        while self.parent[x] != x:
            path.append(x)
            x = self.parent[x]
        for v in reversed(path):                       # compress, accumulating parities towards the root
            p = self.parent[v]
            if p != x:
                self.par[v] ^= self.par[p]
                self.parent[v] = x
        return x
    def add_edge(self, u, v):
        """Returns False if the edge closes an odd cycle."""
        ru, rv = self.find(u), self.find(v)
        pu, pv = self.par[u] if u != ru else 0, self.par[v] if v != rv else 0
        if ru == rv:
            return pu != pv                           # same colour at both ends: odd cycle
        if self.rank[ru] < self.rank[rv]:
            ru, rv, pu, pv = rv, ru, pv, pu
        self.parent[rv] = ru
        self.par[rv] = pu ^ pv ^ 1                    # make u and v get different colours
        if self.rank[ru] == self.rank[rv]:
            self.rank[ru] += 1
        return True

def greedy_matching(edges):
    used, M = set(), []
    for u, v in edges:                                # keep an edge if both ends are still free
        if u not in used and v not in used:
            M.append((u, v)); used |= {u, v}
    return M

def max_bipartite_matching(n_left, edges):
    adj = [[] for _ in range(n_left)]
    for u, v in edges:
        adj[u].append(v)
    match_r = {}
    def augment(u, seen):
        for v in adj[u]:
            if v not in seen:
                seen.add(v)
                if v not in match_r or augment(match_r[v], seen):
                    match_r[v] = u
                    return True
        return False
    return sum(augment(u, set()) for u in range(n_left))

rng = random.Random(2005)
n = 2000
# a bipartite stream: edges between even and odd vertices only, then one extra edge
edges = [(2 * rng.randrange(n // 2), 2 * rng.randrange(n // 2) + 1) for _ in range(3000)]
uf = ParityUnionFind(n)
print("bipartite stream, 3000 edges: odd cycle found?", not all(uf.add_edge(u, v) for u, v in edges))
u, v = edges[0][0], edges[1][0]                       # two even vertices
uf2 = ParityUnionFind(n)
for a, b in edges:
    uf2.add_edge(a, b)
same = uf2.find(u) == uf2.find(v)
print(f"extra edge {u}-{v} (both even, connected: {same}) closes an odd cycle?", not uf2.add_edge(u, v))

# greedy maximal matching vs maximum matching, on a bipartite graph with a bad edge order
L = 100
edges = [(i, i) for i in range(L)] + [(i, (i + 1) % L) for i in range(L)]     # left i -- right i, i+1
rng.shuffle(edges)
M = greedy_matching([(("L", a), ("R", b)) for a, b in edges])
print(f"one pass greedy matching: {len(M)} edges; maximum matching: {max_bipartite_matching(L, edges)}; "
      f"greedy is always >= half")
bipartite stream, 3000 edges: odd cycle found? False
extra edge 922-156 (both even, connected: True) closes an odd cycle? True
one pass greedy matching: 87 edges; maximum matching: 100; greedy is always >= half

On the matching instance (a cycle of length 2L2L written as a bipartite graph, edges in random order), greedy reached 87% of the optimum; the 12\frac{1}{2} guarantee is for the worst order, which an adversary can produce.

In C++

Connectivity of a random graph with a million vertices, one pass over 1.5 million edges, with union-find (union by rank, path halving). The number of components drops slowly at first and then fast, once a giant component forms after about n/2n/2 edges (the Erdős-Rényi phase transition). The state is 5n5n bytes, whatever the number of edges.

cpp · try it yourself
#include <cstdint>
#include <cstdio>
#include <numeric>
#include <random>
#include <utility>
#include <vector>

// Semi-streaming connectivity: one pass over the edges, O(n) words of union-find state.
class UnionFind {
    std::vector<std::uint32_t> parent;
    std::vector<std::uint8_t> rank;
public:
    explicit UnionFind(std::uint32_t n) : parent(n), rank(n, 0) { std::iota(parent.begin(), parent.end(), 0u); }
    std::uint32_t find(std::uint32_t x) {
        while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; }   // path halving
        return x;
    }
    bool unite(std::uint32_t a, std::uint32_t b) {
        a = find(a); b = find(b);
        if (a == b) return false;
        if (rank[a] < rank[b]) std::swap(a, b);
        parent[b] = a;
        if (rank[a] == rank[b]) ++rank[a];
        return true;
    }
};

int main() {
    const std::uint32_t n = 1000000;
    std::mt19937_64 rng(2005);
    UnionFind uf(n);
    std::uint32_t components = n;
    std::uint64_t forest = 0;
    // random edges: the giant component appears once m passes n/2 (Erdos-Renyi)
    for (std::uint64_t m = 1; m <= 1500000; ++m) {
        std::uint32_t u = rng() % n, v = rng() % n;
        if (uf.unite(u, v)) { --components; ++forest; }
        if (m == 250000 || m == 500000 || m == 750000 || m == 1500000)
            std::printf("after %7llu edges: %7u components, %7llu forest edges kept\n",
                (unsigned long long)m, components, (unsigned long long)forest);
    }
    std::printf("memory: %zu bytes for n = %u vertices\n", n * (sizeof(std::uint32_t) + 1), n);
}
after  250000 edges:  750000 components,  250000 forest edges kept
after  500000 edges:  500004 components,  499996 forest edges kept
after  750000 edges:  286788 components,  713212 forest edges kept
after 1500000 edges:   54323 components,  945677 forest edges kept
memory: 5000000 bytes for n = 1000000 vertices

What does not work in one pass

Problem One pass, semi-streaming Notes
connectivity, spanning forest, bipartiteness yes, O(n)O(n) words also with deletions, via sketches (AGM)
minimum spanning tree yes, exact cycle property
maximum matching 12\frac{1}{2}-approximation no better than 1−1e1 - \frac{1}{e} possible
shortest paths (2k−1)(2k-1)-approximation, O(n1+1/k)O(n^{1+1/k}) edges exact distances and BFS trees need many passes in semi-streaming space (Feigenbaum et al., 2005)
minimum cut (1±ε)(1 \pm \varepsilon), via sparsifiers

Test yourself

What memory does the semi-streaming model allow for a graph with nn vertices and mm edges?

  1. O(polylog⁡n)O(\operatorname{polylog} n) bits
  2. O(npolylog⁡n)O(n \operatorname{polylog} n) bits: a few words per vertex, not per edge
  3. O(m)O(m) bits
  4. O(m)O(\sqrt{m}) bits

In the one-pass spanning-forest algorithm, which edges are dropped?

  1. Edges between high-degree vertices
  2. Edges whose ends are already in the same component, since they close a cycle and add no connectivity
  3. Every second edge
  4. Edges that arrive late

How does a parity union-find detect that a graph is not bipartite?

  1. It counts edges
  2. An edge whose two ends are in the same component and have the same parity (colour) relative to the root closes an odd cycle
  3. It runs BFS at the end
  4. It checks vertex degrees

Why is one-pass greedy matching at least half of the maximum?

  1. Because it is a maximum matching
  2. Because the greedy matching is maximal, and every edge of a maximum matching shares an endpoint with some greedy edge, while each greedy edge has only two endpoints
  3. Because the stream is random
  4. Because of union-find