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?- A. 2 [1, 3]
- B. 3 [1, 3, 5]
- C. 2 [3, 5]
- 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
- Problem: Count the strongly connected components and the number of edges in the condensation DAG (Kosaraju). python n = 8 E =…
- Problem: Check whether each graph is bipartite with BFS 2-colouring (graphs may be disconnected). python from collections import deque def…
- Problem: Burst balloons; bursting balloon i earns left × a[i] × right using its current neighbours (1 beyond the ends). Maximise the…
- Problem: Count the ways to split s into a sequence of dictionary words. python def count(s, words): W = set(words); dp = [1] + [0] len(s)…
- Problem: Regular-expression matching where '.' matches any one character and 'x' matches zero or more x (the whole string must match)…
- Problem: Count how many distinct index sequences of s spell t as a subsequence. python def distinct(s, t): dp = [1] + [0] len(t) for c in…