The Semi-Streaming Model
A graph with 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 bits of memory, so polylogarithmic space is out of reach. Feigenbaum, Kannan, McGregor, Suri and Zhang (2005) proposed the semi-streaming model: memory bits, enough to store a few things per vertex but not per edge. For dense graphs, with 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 of a graph on the vertex set , in arbitrary (adversarial) order, each once. In the dynamic model, edges can also be deleted. The algorithm has bits, usually one pass, sometimes a few.
Why and not less: connectivity needs bits in one pass, even for randomized algorithms (Feigenbaum et al., 2005, and Sun and Woodruff, 2015, for the tight ). 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 is set. So any algorithm for connectivity is a protocol for INDEX.
Connectivity and spanning forests
Union-find solves connectivity in one pass with words: keep the partition of the vertices into components seen so far, and merge two components when an edge joins them.
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 componentsThe forest has at most edges, so storing it is also within the budget, and it answers more than connectivity: any two vertices are connected in exactly when they are connected in . The animation runs union-find (union by rank, path compression) on an 8-edge stream; the program prints which edges are kept.
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: 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. words, one pass.
- Minimum spanning forest (weighted edges): keep a spanning forest ; when an edge closes a cycle in , delete the heaviest edge of that cycle (the cycle property of MSTs). The forest stays a minimum spanning forest of the edges seen. words; 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 (Kapralov, 2013), and whether can be beaten at all is a well-known open problem. With several passes, -approximations exist.
- Spanners and distances. Keep an edge only if its endpoints are currently more than apart in the kept graph: the result is a -spanner with edges, which approximates every distance within a factor (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.
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 written as a bipartite graph, edges in random order), greedy reached 87% of the optimum; the 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 edges (the Erdős-Rényi phase transition). The state is bytes, whatever the number of edges.
#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, words | also with deletions, via sketches (AGM) |
| minimum spanning tree | yes, exact | cycle property |
| maximum matching | -approximation | no better than possible |
| shortest paths | -approximation, edges | exact distances and BFS trees need many passes in semi-streaming space (Feigenbaum et al., 2005) |
| minimum cut | , via sparsifiers |
Test yourself
What memory does the semi-streaming model allow for a graph with vertices and edges?
- bits
- bits: a few words per vertex, not per edge
- bits
- bits
In the one-pass spanning-forest algorithm, which edges are dropped?
- Edges between high-degree vertices
- Edges whose ends are already in the same component, since they close a cycle and add no connectivity
- Every second edge
- Edges that arrive late
How does a parity union-find detect that a graph is not bipartite?
- It counts edges
- An edge whose two ends are in the same component and have the same parity (colour) relative to the root closes an odd cycle
- It runs BFS at the end
- It checks vertex degrees
Why is one-pass greedy matching at least half of the maximum?
- Because it is a maximum matching
- 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
- Because the stream is random
- Because of union-find