Data Structures & AlgorithmsVery hardProduct company OA

Problem: Find all critical links (bridges) and critical routers (articulation points) with one DFS using discovery times and low-links.

Problem: Find all critical links (bridges) and critical routers (articulation points) with one DFS using discovery times and low-links.
import sys
sys.setrecursionlimit(10000)
n = 8
edges = [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4), (4, 5), (5, 3), (5, 6), (6, 7)]
adj = [[] for _ in range(n)]
for i, (a, b) in enumerate(edges): adj[a].append((b, i)); adj[b].append((a, i))
tin, low, t, bridges, cut = [-1] * n, [0] * n, 0, [], set()
def dfs(u, pe):
    global t
    tin[u] = low[u] = t; t += 1; kids = 0
    for v, ei in adj[u]:
        if ei == pe: continue
        if tin[v] == -1:
            dfs(v, ei); kids += 1
            low[u] = min(low[u], low[v])
            if low[v] > tin[u]: bridges.append(edges[ei])
            if pe != -1 and low[v] >= tin[u]: cut.add(u)
        else: low[u] = min(low[u], tin[v])
    if pe == -1 and kids > 1: cut.add(u)
dfs(0, -1)
print(sorted(bridges), sorted(cut))
What is printed?
  1. A. [(1, 3), (5, 6), (6, 7)] [1, 3, 5]
  2. B. [(1, 3), (6, 7)] [1, 3, 5, 6]
  3. C. [(5, 6), (6, 7)] [1, 5, 6]
  4. D. [(1, 3), (5, 6), (6, 7)] [1, 3, 5, 6]

Correct answer: D. [(1, 3), (5, 6), (6, 7)] [1, 3, 5, 6]

low[v] is the earliest discovery time reachable from v's subtree with at most one back edge. Edge (u, v) is a bridge iff low[v] > tin[u]; a non-root u is a cut vertex iff some child has low[v] ≥ tin[u]; the root iff it has ≥ 2 DFS children. Triangles {0, 1, 2} and {3, 4, 5} have no bridges inside; (1, 3), (5, 6), (6, 7) are bridges. Vertices 1, 3, 5, 6 are articulation points (6 separates 7). Skipping the parent by EDGE id, not by vertex, keeps parallel edges correct. O(V + E).

More Coding Interview Problems questions

Exams that ask this topic