Given an undirected graph with V vertices (0 .. V-1) and edges edges (no self-loops or duplicate edges), return all bridges — edges whose removal increases the number of connected components. Return each bridge as [min(u,v), max(u,v)], and return the list sorted.
Input: V = 4, edges = [[0,1],[1,2],[2,0],[2,3]] Output: [[2,3]] The triangle 0-1-2 has no bridge; 2-3 is the only link to vertex 3.
Input: V = 4, edges = [[0,1],[1,2],[2,3],[3,0]] Output: [] A single cycle has no bridges.
- 1 <= V <= 10^5 - 0 <= edges.length <= 10^5 - no self-loops or duplicate edges
A bridge is an edge that no cycle covers — remove it and the graph falls apart a little more. Tarjan's algorithm finds all of them in one DFS using two timestamps per vertex:
disc[u] — when u was first discovered.low[u] — the smallest discovery time reachable from u's subtree via tree edges plus one back edge.For a tree edge u → v, the edge is a bridge exactly when low[v] > disc[u]: the subtree rooted at v has no back edge climbing to u or above, so (u, v) is the only link holding it on. Update low[u] from children's low (tree edges) and from disc[w] on back edges. Skip the single edge back to the parent. O(V + E).
The brute force removes each edge and recounts components (O(E · (V + E))) — correct but far slower.
“What's a bridge?”
An edge whose removal increases the number of components.
“Output format?”
Each bridge as [min, max], list sorted.
I DFS tracking discovery times and low-links; a tree edge u-v is a bridge when low[v] > disc[u].
That means v's subtree has no back edge climbing above u, so the edge isn't on any cycle.
Worked example — V = 4, edges [[0,1],[1,2],[2,0],[2,3]]
0-1-2 form a cycle -> none are bridges (each has a back edge) 2-3 is the only link to 3 -> bridge answer = [[2,3]]
A back edge covering an edge disqualifies it.
v's subtree can't climb above u.
disc and low computed in one pass.
| Remove each edge | Tarjan (disc/low) | |
|---|---|---|
| Idea | recount components without it | one DFS with low-links |
| Time | O(E·(V+E)) | O(V+E) |
| Bridges | component count increases | low[v] > disc[u] |
Both find the same bridges. Full code is in the Approaches selector below.
Key takeaway
A bridge is an edge on no cycle. Tarjan's DFS finds them via low-links: a tree edge u-v is a bridge iff low[v] > disc[u]. O(V+E).
dfs(u, parent): for child v: if low[v] > disc[u] -> bridge (u,v)