TExcelTAD
Home › Graph Algorithms › The Parenthesis and White-Path Theorems

The Parenthesis and White-Path Theorems

Write an opening bracket "(u" when depth-first search discovers uu and a closing bracket "u)" when it finishes uu. The result is always a correctly nested expression, like a well-formed arithmetic formula. That is the parenthesis theorem, and together with the white-path theorem, which says exactly which vertices end up below uu in the depth-first forest, it is the tool behind every DFS-based proof in this course: cycle detection, topological sort and strongly connected components.

The parenthesis theorem

Theorem (parenthesis structure). In any DFS of a directed or undirected graph, for any two vertices uu and vv, exactly one of the following holds:

  1. the intervals [u.d,u.f][u.d, u.f] and [v.d,v.f][v.d, v.f] are disjoint, and neither vertex is a descendant of the other in the depth-first forest;
  2. [u.d,u.f][u.d, u.f] lies entirely inside [v.d,v.f][v.d, v.f], and uu is a descendant of vv;
  3. [v.d,v.f][v.d, v.f] lies entirely inside [u.d,u.f][u.d, u.f], and vv is a descendant of uu.

Two intervals never partly overlap.

Proof

Assume u.d<v.du.d < v.d (the other case is symmetric). Case v.d<u.fv.d < u.f: vv was discovered while uu was gray, so uu was on the recursion path at that moment and vv is a descendant of uu. Since vv was discovered after uu, DFS-VISIT(v)(v) is a call nested inside DFS-VISIT(u)(u), and a nested call returns first: v.f<u.fv.f < u.f. So u.d<v.d<v.f<u.fu.d < v.d < v.f < u.f, which is case 3. Case u.f<v.du.f < v.d: then u.d<u.f<v.d<v.fu.d < u.f < v.d < v.f, so the intervals are disjoint. Neither vertex was gray while the other was discovered, so neither is an ancestor of the other: case 1.

Corollary (nesting of descendants). vv is a proper descendant of uu if and only if u.d<v.d<v.f<u.fu.d < v.d < v.f < u.f.

The program prints the bracket sequence for the example graph of the DFS lesson and then checks the theorem on every pair of vertices of 300 random directed graphs.

python · try it yourself
import random

def dfs(adj):
    d, f, parent, events, time = {}, {}, {}, [], 0
    def visit(u):
        nonlocal time
        time += 1; d[u] = time; events.append(f"({u}")
        for v in adj[u]:
            if v not in d:
                parent[v] = u
                visit(v)
        time += 1; f[u] = time; events.append(f"{u})")
    for u in adj:
        if u not in d:
            visit(u)
    return d, f, parent, events

adj = {"A": ["B", "D", "E"], "B": ["C", "D"], "C": ["A"], "D": ["C"], "E": ["D", "F"], "F": ["E"], "G": ["F"]}
print(" ".join(dfs(adj)[3]))

def is_descendant(parent, v, u):              # walk up from v looking for u
    while v in parent:
        v = parent[v]
        if v == u:
            return True
    return False

rng = random.Random(5)
pairs = nested = disjoint = 0
for trial in range(300):
    n = rng.randint(2, 15)
    g = {u: [v for v in range(n) if v != u and rng.random() < 0.2] for u in range(n)}
    d, f, parent, _ = dfs(g)
    for u in g:
        for v in g:
            if u == v:
                continue
            pairs += 1
            inside = d[u] < d[v] < f[v] < f[u]
            apart = f[u] < d[v] or f[v] < d[u]
            assert inside or apart or (d[v] < d[u] < f[u] < f[v])        # never a partial overlap
            assert inside == is_descendant(parent, v, u)                # the corollary
            nested += inside
            disjoint += apart
print(f"{pairs} ordered pairs: {nested} with v inside u, {nested} with u inside v, {disjoint} disjoint, 0 partial overlaps")
(A (B (C C) (D D) B) (E (F F) E) A) (G G)
22872 ordered pairs: 6158 with v inside u, 6158 with u inside v, 10556 disjoint, 0 partial overlaps

The white-path theorem

Which vertices become descendants of uu? Not simply the ones reachable from uu: in the example, DD is reachable from EE, but it is a descendant of BB, because DD was already black when EE was discovered. The precise answer looks at the moment uu is discovered.

Theorem (white path). In a depth-first forest of a (directed or undirected) graph, vv is a descendant of uu if and only if at time u.du.d there is a path from uu to vv consisting entirely of white vertices (apart from uu itself, which has just turned gray).

Proof

Only if. If v=uv = u the path is just uu. If vv is a proper descendant, then u.d<v.du.d < v.d by the corollary, so vv is white at time u.du.d. The same holds for every vertex on the tree path from uu to vv, since each is a descendant of uu. So the tree path is a white path.

If. Suppose there is a white path from uu to vv at time u.du.d, but vv does not become a descendant of uu. Among the vertices of the path that do not become descendants, let vv be the one closest to uu, and let ww be its predecessor on the path. Then ww is a descendant of uu (possibly uu itself), so w.f≤u.fw.f \le u.f. Because vv was white at time u.du.d, u.d<v.du.d < v.d. DFS cannot finish ww while its neighbour vv is still white, so v.d<w.f≤u.fv.d < w.f \le u.f. So u.d<v.d<u.fu.d < v.d < u.f: vv is discovered while uu is gray. By the parenthesis theorem its interval must then lie inside uu's, so vv is a descendant of uu, a contradiction.

A vertex is white at time u.du.d exactly when its discovery time is later than u.du.d. So the theorem can be checked directly: vv is a descendant of uu if and only if vv is reachable from uu using only vertices ww with w.d≥u.dw.d \ge u.d.

python · try it yourself
import random

def dfs(adj):
    d, f, parent, time = {}, {}, {}, 0
    def visit(u):
        nonlocal time
        time += 1; d[u] = time
        for v in adj[u]:
            if v not in d:
                parent[v] = u
                visit(v)
        time += 1; f[u] = time
    for u in adj:
        if u not in d:
            visit(u)
    return d, f, parent

def white_reachable(adj, d, u):
    """Vertices reachable from u through vertices that were still white at time d[u]."""
    seen, stack = {u}, [u]
    while stack:
        x = stack.pop()
        for y in adj[x]:
            if y not in seen and d[y] > d[u]:
                seen.add(y)
                stack.append(y)
    return seen

rng = random.Random(12)
checked = 0
for trial in range(300):
    n = rng.randint(2, 15)
    g = {u: [v for v in range(n) if v != u and rng.random() < 0.2] for u in range(n)}
    d, f, parent = dfs(g)
    for u in g:
        descendants = {v for v in g if d[u] <= d[v] and f[v] <= f[u]}     # by the corollary
        assert descendants == white_reachable(g, d, u)
        checked += 1
print(f"white-path theorem confirmed for {checked} vertices in 300 random graphs")

adj = {"A": ["B", "D", "E"], "B": ["C", "D"], "C": ["A"], "D": ["C"], "E": ["D", "F"], "F": ["E"], "G": ["F"]}
d, f, _ = dfs(adj)
for u in "BEG":
    print(f"white path from {u} at time {d[u]}: {sorted(white_reachable(adj, d, u))}")
white-path theorem confirmed for 2563 vertices in 300 random graphs
white path from B at time 2: ['B', 'C', 'D']
white path from E at time 8: ['E', 'F']
white path from G at time 13: ['G']

At time E.d=8E.d = 8, vertices BB, CC and DD are already black, so the only white path from EE leads to FF: EE's subtree is {E,F}\{E, F\}. When GG is discovered, everything else is black and its subtree is just {G}\{G\}.

Application: cycles and back edges

Theorem. A directed graph GG is acyclic if and only if a DFS of GG produces no back edges.

Proof

A back edge gives a cycle. If (u,v)(u, v) is a back edge, vv is an ancestor of uu, so the tree path from vv to uu followed by (u,v)(u, v) is a cycle.

A cycle gives a back edge. Let cc be a cycle and vv its vertex discovered first, and let (u,v)(u, v) be the edge of cc entering vv. At time v.dv.d all other vertices of cc are white, so the rest of the cycle is a white path from vv to uu. By the white-path theorem uu becomes a descendant of vv, so when DFS explores (u,v)(u, v), vv is an ancestor of uu that is still gray: a back edge.

The proof does not depend on the order in which DFS picks its start vertices or neighbours: every DFS of a cyclic graph finds a back edge. That is why one Θ(V+E)\Theta(V + E) search decides whether a dependency graph can be scheduled at all, the first step of topological sorting.

Test yourself

DFS gives uu the interval [3,10][3, 10]. Which interval is impossible for another vertex vv?

  1. [4,7][4, 7]
  2. [1,12][1, 12]
  3. [11,14][11, 14]
  4. [5,12][5, 12]

At the moment uu is discovered, vv is reachable from uu, but every path from uu to vv passes through a black vertex. Is vv a descendant of uu?

  1. Yes, always
  2. Not necessarily; by the white-path theorem it is a descendant only if a path of white vertices exists
  3. Only in undirected graphs
  4. Only if vv is gray

In the proof that a cycle forces a back edge, which vertex of the cycle is chosen?

  1. The one with the largest finishing time
  2. The first vertex of the cycle that DFS discovers
  3. The vertex with the smallest name
  4. The last vertex finished