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?- A. [(1, 3), (5, 6), (6, 7)] [1, 3, 5]
- B. [(1, 3), (6, 7)] [1, 3, 5, 6]
- C. [(5, 6), (6, 7)] [1, 5, 6]
- 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
- Problem: A drone must fly every route leg exactly once starting at P, choosing the alphabetically smallest destination whenever possible…
- Problem: Assign interns to projects; intern u may take only projects in adj[u], each project at most one intern. Maximum bipartite…
- Problem: For every warehouse in a tree network, compute the sum of distances to all other warehouses with two passes (rerooting)…
- Problem: Count integers in [1, N] divisible by at least one of the given numbers using inclusion–exclusion with LCMs (N up to 10⁹, so no…
- Problem: Compute C(n, r) mod a SMALL prime p = 7 when n ≥ p: Lucas' theorem versus factorials with Fermat inverses. python p = 7 fact =…
- Problem: Count ways to climb n stairs with steps of 1 or 3, modulo 10⁹ + 7, using a 3 × 3 matrix power so that n up to 10¹⁸ is fine…