Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Find the bridges and articulation points of an undirected graph using DFS discovery times and low-links.

Problem: Find the bridges and articulation points of an undirected graph using DFS discovery times and low-links.
import sys
sys.setrecursionlimit(10000)
n = 7
edges = [(0,1),(1,2),(2,0),(1,3),(3,4),(4,5),(5,3),(5,6)]
g = [[] for _ in range(n)]
for u, v in edges: g[u].append(v); g[v].append(u)
tin, low, t = [-1] * n, [0] * n, [0]
bridges, cut = [], set()
def dfs(u, p):
    tin[u] = low[u] = t[0]; t[0] += 1; kids = 0
    for v in g[u]:
        if v == p: continue
        if tin[v] != -1: low[u] = min(low[u], tin[v])
        else:
            dfs(v, u); kids += 1
            low[u] = min(low[u], low[v])
            if low[v] > tin[u]: bridges.append((u, v))
            if p != -1 and low[v] >= tin[u]: cut.add(u)
    if p == -1 and kids > 1: cut.add(u)
dfs(0, -1)
print(len(bridges), sorted(cut))
What is printed?
  1. A. 2 [1, 3]
  2. B. 3 [1, 3, 5]
  3. C. 2 [3, 5]
  4. D. 2 [1, 3, 5]

Correct answer: D. 2 [1, 3, 5]

Two triangles (0-1-2 and 3-4-5) are joined by the edge 1–3, and 6 hangs off 5. The bridges are 1–3 and 5–6; removing 1, 3 or 5 disconnects the graph, so the articulation points are [1, 3, 5]. Bridge endpoints are not always cut vertices (a leaf like 6 is not).

More Coding Interview Problems questions

Exams that ask this topic