Sub topic 11
Weakly Connected Components
This chapter assumes you have worked through the earlier chapters on adjacency lists, BFS and DFS labeling, and union-find. It also assumes you know the difference between directed and undirected edges. The previous chapter showed that direction splits "connected" into two separate questions. This chapter takes the simpler one: which vertices belong together if you ignore the arrows?
The Definition
A directed graph is weakly connected if replacing every directed edge u → v with an undirected edge u — v produces a connected undirected graph. A weakly connected component (WCC) is a maximal set of vertices that is weakly connected in this sense.
The undirected graph you get by dropping the arrows is called the underlying undirected graph. The WCCs of a directed graph are exactly the connected components of its underlying undirected graph. So you need no new algorithm. You only have to build the right adjacency list.
Being in the same WCC says very little about reachability. Two vertices can share a weak component even though neither can reach the other by following arrows. Take the edges 0 → 1 and 2 → 1. Vertices 0 and 2 are in the same WCC because both touch 1. Still, no directed path runs from 0 to 2 or from 2 to 0.
This graph is the running example for the whole chapter. It has three WCCs: {0, 1, 2}, {3, 4, 5}, and {6}.
Computing WCCs by Symmetrizing the Adjacency List
To get the underlying undirected graph, add each directed edge to the adjacency lists of both endpoints. After that, the BFS labeling code from the earlier chapter works unchanged.
from collections import deque
def weakly_connected_components(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v) # follow the edge forward
adj[v].append(u) # and also backward
label = [-1] * n
count = 0
for start in range(n):
if label[start] != -1:
continue
label[start] = count
queue = deque([start])
while queue:
u = queue.popleft()
for v in adj[u]:
if label[v] == -1:
label[v] = count
queue.append(v)
count += 1
return count, label
edges = [(0, 1), (2, 1), (3, 4), (4, 5), (5, 3)]
print(weakly_connected_components(7, edges))
# (3, [0, 0, 0, 1, 1, 1, 2])The only change from undirected labeling is the comment on the second append. In the undirected chapter, that line was there because the edge had no direction. Here it is there because you are deliberately throwing the direction away.
Cost
Every directed edge becomes two adjacency entries, so the adjacency list holds 2E entries, the same as for an undirected graph with E edges. Time stays O(V + E) and space stays O(V + E). If you already have an out-neighbor list and cannot afford a second copy, you can store a separate in-neighbor list and scan both during traversal. That uses the same memory but keeps the two directions apart, which is useful when other code needs the original out-edges.
The Most Common Bug: Following Only Out-Edges
The usual mistake is to reuse a directed adjacency list (out-edges only) and run the standard labeling loop on it. The code runs, prints plausible numbers, and is wrong.
def buggy_wcc(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v) # out-edges only: this is the bug
label = [-1] * n
count = 0
for start in range(n):
if label[start] != -1:
continue
label[start] = count
stack = [start]
while stack:
u = stack.pop()
for v in adj[u]:
if label[v] == -1:
label[v] = count
stack.append(v)
count += 1
return count, label
edges = [(0, 1), (2, 1), (3, 4), (4, 5), (5, 3)]
print(buggy_wcc(7, edges))
# (4, [0, 0, 1, 2, 2, 2, 3])Here is what goes wrong. The traversal from 0 reaches 1 and labels it. When the outer loop gets to 2, it can follow 2 → 1, but 1 is already labeled, so the code never connects 2's group to 0's group. Vertex 2 gets its own label.
This bug does more than produce a wrong count. The output depends on vertex numbering. If you renamed vertex 2 to be 0, the traversal from it would claim 1, and the old vertex 0 would end up alone. Each label means "the set of not-yet-labeled vertices reachable from this start", which is not a property of the graph at all.
The cycle {3, 4, 5} happened to come out right in the buggy version, because every vertex in a cycle is reachable from every other. That is why the bug can survive casual testing: on graphs made of cycles, or on graphs where every edge points from lower to higher IDs with a convenient start order, it looks correct.
Computing WCCs with Union-Find
Union-find never looks at edge direction. union(u, v) and union(v, u) do the same thing. That makes it a natural fit for WCCs, and it lets you handle directed edges as a stream without building any adjacency list.
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.components = n
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # path halving
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
self.components -= 1
return True
edges = [(0, 1), (2, 1), (3, 4), (4, 5), (5, 3)]
ds = DisjointSet(7)
for u, v in edges:
ds.union(u, v) # direction is simply ignored
print(ds.components) # 3
print(ds.find(0) == ds.find(2)) # True
print(ds.find(0) == ds.find(3)) # FalseThis version uses path halving, a one-pass variant of the path compression shown earlier. Both give the same near-constant amortized cost. If edges arrive over time, as in a log of "service A called service B" events, union-find keeps the WCC count current after each edge. The incremental connectivity chapter covered this for undirected graphs, and it carries over to WCCs with no changes.
How WCCs Relate to SCCs
Every strongly connected component lies entirely inside one weakly connected component. If u and v can reach each other along arrows, they are certainly connected once you ignore the arrows. So the SCCs partition each WCC into finer pieces.
In the running example, the SCCs are {0}, {1}, {2}, {3, 4, 5}, and {6}: five SCCs inside three WCCs. The WCC {0, 1, 2} breaks into three single-vertex SCCs because it has no cycle. The WCC {3, 4, 5} is one cycle, so it is also one SCC.
| Property | Weakly connected component | Strongly connected component |
|---|---|---|
| Uses edge direction | No | Yes |
| Membership test | Path exists in underlying undirected graph | Directed paths exist both ways |
| Algorithm | Symmetrized BFS/DFS, or union-find | Kosaraju or Tarjan (next chapters) |
| Works on a stream of edges | Yes, with union-find | Not with plain union-find |
| Count compared with the other | At most the SCC count | At least the WCC count |
| Single-vertex component means | Vertex has no edges at all | Vertex lies on no cycle |
The last row is a common source of confusion. A singleton WCC is an isolated vertex. A singleton SCC can have many edges, as long as none of them lead back to it.
Edge Cases
- Isolated vertices. A vertex that appears in no edge is still its own WCC. Your function must take the vertex count
n(or an explicit vertex list), not infer vertices from the edges. Otherwise vertex 6 in the example disappears. - Self-loops. An edge
u → uappendsuto its own list twice in the symmetrized version. Thelabelcheck makes this harmless, andunion(u, u)returnsFalse. - Antiparallel and duplicate edges. The pair
u → v,v → ubecomes four adjacency entries. The output stays correct, and the extra entries only add work in proportion to the input. - Vertices that are not integers. With string or object IDs, use a dict of lists for adjacency and a dict or set for labels. Map IDs to
0..n-1first if you want the array-based union-find. - Very large components. Use BFS or an explicit stack, as above. A recursive DFS on a long chain will hit Python's recursion limit.
When WCCs Are the Right Question
Use WCCs when you want to know which parts of a directed system have no relationship at all, whatever the direction. Typical cases:
- Splitting a package dependency graph into independent groups that can be built or deployed separately.
- Finding clusters in a follower graph or a hyperlink crawl before running heavier analysis on each cluster.
- Sharding work: vertices in different WCCs never interact, so they can be processed in parallel.
Use SCCs instead when the question involves mutual reachability, such as detecting dependency cycles or finding groups of web pages that all link to each other.
Exercise
A directed graph has vertices 0 to 5 and edges 0→1, 1→2, 3→2, 4→5, 5→4. List its weakly connected components and its strongly connected components.
Show answer
The WCCs are {0, 1, 2, 3} (3→2 joins 3 to the chain 0→1→2), and {4, 5}. That makes 2 WCCs. The SCCs are {0}, {1}, {2}, {3}, and {4, 5}, which makes 5 SCCs. The first WCC has no cycle, so each of its vertices is its own SCC. The second WCC is a 2-cycle, so it is a single SCC.
Exercise
Run buggy_wcc from this chapter on n = 3 with edges [(1, 0), (2, 0)]. What does it return, and why is it wrong?
Show answer
It returns (3, [0, 1, 2]). From start 0 there are no out-edges, so 0 is alone. From 1 it follows 1→0, but 0 is already labeled, so 1 gets a new label. The same happens to 2. The correct answer is a single WCC, (1, [0, 0, 0]), because all three vertices touch vertex 0 once direction is ignored.
Exercise
You receive directed edges one at a time from a network log and must report the number of weakly connected components after each edge. Which method from this chapter fits, and what is the cost per edge?
Show answer
Use union-find. Call union(u, v) for each edge, ignoring direction, and read the running components counter. With union by size plus path compression (or path halving), each edge costs O(α(n)) amortized time, which is effectively constant. Rerunning BFS after every edge would cost O(V + E) per edge.