TExcelTAD
Home › Advanced & Succinct Data Structures › Fully Dynamic Connectivity in Polylogarithmic Time

Fully Dynamic Connectivity in Polylogarithmic Time

The full problem: a graph on nn vertices whose edges are inserted and deleted arbitrarily, with queries CONNECTED(u,v)(u, v). Forests are easy with Euler-tour trees. General graphs are hard because of deletions of tree edges: when an edge of a spanning forest disappears, the two halves may still be connected through some non-tree edge, the replacement edge, and finding it seems to require looking at many edges.

The algorithm of Holm, de Lichtenberg and Thorup (2001), usually called HDT, solves this with

O(lg⁡2n) amortized time per update,O(lg⁡n/lg⁡lg⁡n) worst-case time per queryO(\lg^2 n) \text{ amortized time per update}, \qquad O(\lg n / \lg \lg n) \text{ worst-case time per query}

deterministically. This lesson is an overview: it explains the level structure and the amortization argument, and runs the level logic with plain adjacency sets in place of Euler-tour trees, so the program shows correctness and counts promotions rather than achieving the time bound.

Earlier approaches

Result Update time Notes
recompute components O(m)O(m) baseline
Frederickson (1985) O(m)O(\sqrt{m}) worst case topology trees on a spanning forest
Eppstein, Galil, Italiano and Nissenzweig (1997) O(n)O(\sqrt{n}) worst case sparsification on top of Frederickson
Henzinger and King (1995) O(lg⁡3n)O(\lg^3 n) expected amortized randomized; introduced Euler-tour trees and levels
Holm, de Lichtenberg and Thorup (2001) O(lg⁡2n)O(\lg^2 n) amortized deterministic
Thorup (2000) O(lg⁡n(lg⁡lg⁡n)3)O(\lg n (\lg \lg n)^3) expected amortized randomized
Wulff-Nilsen (2013) O(lg⁡2n/lg⁡lg⁡n)O(\lg^2 n / \lg \lg n) amortized deterministic
Kapron, King and Mountjoy (2013) polylogarithmic worst case Monte Carlo (may err with small probability)

The lower bound of Pătrașcu and Demaine (2006) says Ω(lg⁡n)\Omega(\lg n) cell probes are needed per operation (amortized, for the slower of updates and queries), so HDT is within a lg⁡n\lg n factor of optimal.

Levels

Each edge ee has a level ℓ(e)∈{0,1,…,⌊lg⁡n⌋}\ell(e) \in \{0, 1, \ldots, \lfloor \lg n \rfloor\}. New edges start at level 0, and levels only increase. Let GiG_i be the graph of edges with level at least ii, so G=G0⊇G1⊇⋯G = G_0 \supseteq G_1 \supseteq \cdots. The algorithm maintains a spanning forest FF of GG and, for each ii, the forest Fi=F∩GiF_i = F \cap G_i of tree edges with level at least ii, each in its own Euler-tour tree structure. Two invariants hold at all times:

  1. Size: every connected component of GiG_i has at most n/2in / 2^i vertices. (So levels above lg⁡n\lg n are never needed.)
  2. Maximality: FF is a maximum spanning forest of GG when edges are weighted by their levels; in particular FiF_i is a spanning forest of GiG_i. Equivalently, if a non-tree edge (u,v)(u, v) has level ii, then uu and vv are connected in FiF_i.

A query asks whether uu and vv are in the same tree of F0F_0: one Euler-tour tree query, O(lg⁡n)O(\lg n), or O(lg⁡n/lg⁡lg⁡n)O(\lg n / \lg \lg n) if the Euler-tour trees are B-trees of degree Θ(lg⁡n)\Theta(\lg n).

Updates

Insert (u,v)(u, v): give it level 0. If uu and vv are not connected in F0F_0, add it to FF (to F0F_0's Euler-tour trees). Otherwise it is a non-tree edge.

Delete a non-tree edge: remove it from the incidence lists. Done.

Delete a tree edge (u,v)(u, v) of level ℓ\ell: remove it from F0,…,FℓF_0, \ldots, F_\ell. The tree of FℓF_\ell that contained it splits into TuT_u and TvT_v. By maximality, any replacement edge has level at most ℓ\ell. Search for one level by level, from i=ℓi = \ell down to 00:

text
for i = l down to 0
    let T be the smaller of the two trees T_u, T_v of F_i      // |T| <= half of the old tree, so <= n / 2^(i+1)
    raise every level-i tree edge of T to level i + 1           // keeps the size invariant at level i + 1
    for each level-i non-tree edge (x, y) with x in T
        if y is not in T                                        // a replacement edge
            make (x, y) a tree edge: add it to F_0, ..., F_i; stop
        else
            raise (x, y) to level i + 1                         // both ends in T: pay for the scan

Raising the edges of TT to level i+1i + 1 is allowed because TT has at most half the vertices of a component of GiG_i, so at most n/2i+1n / 2^{i+1}, and the size invariant holds for Gi+1G_{i+1}. Raising a non-tree edge with both ends in TT keeps maximality, since its ends are now connected in Fi+1F_{i+1}.

Finding the edges fast. Each Euler-tour tree node of a vertex carries two flags: "this vertex has incident level-ii tree edges" and "this vertex has incident level-ii non-tree edges", and every BST node knows whether any node in its subtree is flagged. Then each edge to raise or scan is found in O(lg⁡n)O(\lg n) time by descending along flagged subtrees.

The amortized bound

Every scanned non-tree edge either is the replacement (once per deletion) or is raised one level. Every tree edge processed is raised. An edge's level never decreases and is at most lg⁡n\lg n, so each edge is raised at most lg⁡n\lg n times over its lifetime, and each raise costs O(lg⁡n)O(\lg n) (Euler-tour tree updates at one level). Charging the raises to the insertion of the edge:

O(lg⁡n) raises per edge×O(lg⁡n) per raise=O(lg⁡2n) amortized per updateO(\lg n) \text{ raises per edge} \times O(\lg n) \text{ per raise} = O(\lg^2 n) \text{ amortized per update}

The remaining work per deletion is O(lg⁡n)O(\lg n) levels times O(lg⁡n)O(\lg n) for the cut and the replacement, also O(lg⁡2n)O(\lg^2 n).

The level logic in a program

The program keeps FiF_i as adjacency sets and finds components by depth-first search, which costs far more than Euler-tour trees but runs exactly the same level decisions. It performs about 4500 random insertions and deletions on 64 vertices, checks every query against a search of the whole graph, and checks the size invariant every 500 steps.

python · try it yourself
import random

class LevelConnectivity:
    """Holm-de Lichtenberg-Thorup levels, with plain adjacency sets instead of Euler-tour trees."""
    def __init__(self, n):
        self.n, self.L = n, max(1, (n - 1).bit_length())      # levels 0..L-1 suffice: n / 2^L < 1
        self.level, self.tree = {}, set()
        self.F = [[set() for _ in range(n)] for _ in range(self.L + 1)]   # F[i]: tree edges of level >= i
        self.N = [[set() for _ in range(n)] for _ in range(self.L + 1)]   # N[i][v]: non-tree edges of level i at v
        self.promotions = 0
    def _component(self, i, s):
        seen, stack = {s}, [s]
        while stack:
            x = stack.pop()
            for y in self.F[i][x]:
                if y not in seen: seen.add(y); stack.append(y)
        return seen
    def connected(self, u, v):
        return v in self._component(0, u)                     # an ETT query in the real structure
    def insert(self, u, v):
        e = (min(u, v), max(u, v))
        self.level[e] = 0
        if self.connected(u, v):
            self.N[0][u].add(v); self.N[0][v].add(u)
        else:
            self.tree.add(e); self.F[0][u].add(v); self.F[0][v].add(u)
    def delete(self, u, v):
        e = (min(u, v), max(u, v))
        l = self.level.pop(e)
        if e not in self.tree:
            self.N[l][u].discard(v); self.N[l][v].discard(u); return
        self.tree.discard(e)
        for i in range(l + 1):
            self.F[i][u].discard(v); self.F[i][v].discard(u)
        for i in range(l, -1, -1):
            Tu, Tv = self._component(i, u), self._component(i, v)
            T = Tu if len(Tu) <= len(Tv) else Tv               # the smaller side: at most half
            for x in T:                                        # its level-i tree edges move up
                for y in self.F[i][x]:
                    f = (min(x, y), max(x, y))
                    if x < y and self.level[f] == i:
                        self.level[f] = i + 1; self.promotions += 1
                        self.F[i + 1][x].add(y); self.F[i + 1][y].add(x)
            for x in sorted(T):                                # scan level-i non-tree edges at T
                for y in sorted(self.N[i][x]):
                    self.N[i][x].discard(y); self.N[i][y].discard(x)
                    f = (min(x, y), max(x, y))
                    if y not in T:                             # a replacement edge: reconnect at level i
                        self.tree.add(f)
                        for j in range(i + 1):
                            self.F[j][x].add(y); self.F[j][y].add(x)
                        return
                    self.level[f] = i + 1; self.promotions += 1  # both ends in T: push it up
                    self.N[i + 1][x].add(y); self.N[i + 1][y].add(x)
    def check_invariant(self):                                 # components of F[i] have <= n / 2^i vertices
        for i in range(self.L + 1):
            seen = set()
            for s in range(self.n):
                if s not in seen:
                    c = self._component(i, s); seen |= c
                    assert len(c) <= self.n >> i or len(c) == 1, (i, len(c))

rng = random.Random(2001)
n = 64
g, edges = LevelConnectivity(n), set()
adj = [set() for _ in range(n)]
def dfs(u, v):
    seen, stack = {u}, [u]
    while stack:
        x = stack.pop()
        for y in adj[x]:
            if y not in seen: seen.add(y); stack.append(y)
    return v in seen
updates = 0
for step in range(6000):
    r = rng.random()
    if r < 0.5 and len(edges) < 150:
        u, v = rng.randrange(n), rng.randrange(n)
        e = (min(u, v), max(u, v))
        if u == v or e in edges: continue
        g.insert(u, v); edges.add(e); adj[u].add(v); adj[v].add(u); updates += 1
    elif r < 0.8 and edges:
        e = sorted(edges)[rng.randrange(len(edges))]
        g.delete(*e); edges.discard(e); adj[e[0]].discard(e[1]); adj[e[1]].discard(e[0]); updates += 1
    else:
        u, v = rng.randrange(n), rng.randrange(n)
        assert g.connected(u, v) == dfs(u, v)
    if step % 500 == 0: g.check_invariant()
print(f"{updates} updates on {n} vertices, every query agrees with DFS, invariant holds")
print(f"highest level used: {max(g.level.values())} (levels allowed: 0..{g.L})")
print(f"edge promotions: {g.promotions}, i.e. {g.promotions / updates:.2f} per update (each edge at most {g.L} times)")
4549 updates on 64 vertices, every query agrees with DFS, invariant holds
highest level used: 3 (levels allowed: 0..6)
edge promotions: 1293, i.e. 0.28 per update (each edge at most 6 times)

The levels stay low because random graphs rarely force many raises, and each edge is raised far fewer than lg⁡n\lg n times on average. The amortized bound charges the worst case: an adversary can make edges climb all the way.

python · try it yourself
import math

# Amortized cost of HDT per update, in units of ETT operations of cost lg n each:
# every edge can be promoted at most lg n times, and a promotion costs O(lg n).
for n in [2 ** 10, 2 ** 20, 2 ** 30]:
    lg = math.log2(n)
    print(f"n = 2^{int(lg)}: levels {int(lg) + 1:2}, promotions per edge <= {int(lg):2}, "
          f"update ~ lg^2 n = {lg ** 2:5.0f}, query ~ lg n / lg lg n = {lg / math.log2(lg):4.1f}, "
          f"sqrt(n) = {math.sqrt(n):7.0f}")
n = 2^10: levels 11, promotions per edge <= 10, update ~ lg^2 n =   100, query ~ lg n / lg lg n =  3.0, sqrt(n) =      32
n = 2^20: levels 21, promotions per edge <= 20, update ~ lg^2 n =   400, query ~ lg n / lg lg n =  4.6, sqrt(n) =    1024
n = 2^30: levels 31, promotions per edge <= 30, update ~ lg^2 n =   900, query ~ lg n / lg lg n =  6.1, sqrt(n) =   32768

For a million vertices, lg⁡2n=400\lg^2 n = 400 Euler-tour operations against n=1000\sqrt{n} = 1000 for sparsification, and the gap grows quickly with nn. In practice the constants of HDT are moderate, and implementations (Iyer, Karger, Rahul and Thorup, 2001) found it competitive with simpler heuristics on hard inputs.

Note: Only connectivity is polylogarithmic. Dynamic versions of other problems behave differently: dynamic minimum spanning forest has deterministic O(lg⁡4n)O(\lg^4 n) amortized updates (HDT, same paper), dynamic 2-edge connectivity O(lg⁡4n)O(\lg^4 n) amortized, and for some problems, such as dynamic reachability in directed graphs, polylogarithmic updates are believed impossible under fine-grained hardness conjectures.

Test yourself

Why does HDT raise the tree edges of the **smaller** tree TT to level i+1i + 1?

  1. To shorten the search
  2. Because TT has at most half the vertices of its component of GiG_i, so the size invariant n/2i+1n / 2^{i+1} still holds at level i+1i + 1
  3. Because the larger tree is already at level i+1i + 1
  4. To make the forest unique

Where does the O(lg⁡2n)O(\lg^2 n) amortized update bound come from?

  1. Each deletion scans O(lg⁡2n)O(\lg^2 n) edges
  2. Each edge is raised at most lg⁡n\lg n times, each raise costs O(lg⁡n)O(\lg n) in the Euler-tour trees, and raises are charged to insertions
  3. The Euler-tour trees have depth lg⁡2n\lg^2 n
  4. Queries cost O(lg⁡2n)O(\lg^2 n)

Which statement about lower bounds for dynamic connectivity is correct?

  1. O(1)O(1) per operation is possible
  2. Pătrașcu and Demaine proved Ω(lg⁡n)\Omega(\lg n) cell probes per operation (amortized, for the slower of updates and queries)
  3. There is no known lower bound
  4. The lower bound is Ω(n)\Omega(\sqrt{n})