Data Structures & AlgorithmsVery hardProduct company OA
Problem: Count the strongly connected components of a directed graph with Kosaraju's algorithm (DFS finishing order, then DFS on the reversed graph). Also list component sizes.
Problem: Count the strongly connected components of a directed graph with Kosaraju's algorithm (DFS finishing order, then DFS on the reversed graph). Also list component sizes.
def scc_count(n, edges):
g = [[] for _ in range(n)]; rg = [[] for _ in range(n)]
for u, v in edges: g[u].append(v); rg[v].append(u)
seen, order = [False] * n, []
def dfs1(u):
seen[u] = True
for v in g[u]:
if not seen[v]: dfs1(v)
order.append(u)
for i in range(n):
if not seen[i]: dfs1(i)
comp = [-1] * n; c = 0
def dfs2(u):
comp[u] = c
for v in rg[u]:
if comp[v] == -1: dfs2(v)
for u in reversed(order):
if comp[u] == -1: dfs2(u); c += 1
return c, sorted([comp.count(k) for k in range(c)], reverse=True)
print(scc_count(8, [(0, 1), (1, 2), (2, 0), (2, 3), (3, 4), (4, 5), (5, 3), (6, 5), (6, 7), (7, 6)]))What is printed?- A. (3, [3, 3, 2])
- B. (4, [3, 3, 1, 1])
- C. (2, [5, 3])
- D. (1, [8])
Correct answer: A. (3, [3, 3, 2])
Cycles 0→1→2→0, 3→4→5→3 and 6⇄7 are the SCCs; the edges 2→3 and 6→5 go one way only, so they do not merge components (undirected connectivity would give a single component of 8). The node finishing last in pass 1 lies in a 'source' component; exploring the reversed graph from it cannot leak into other components. O(V + E).
More Coding Interview Problems questions
- Problem: Stones sit on grid points; a stone may be removed if another remaining stone shares its row or column. Maximum removable = stones…
- Problem: Build row k of Pascal's triangle (row 0 = [1]) by adding neighbouring entries of the previous row. python def pascalrow(k): row =…
- Problem: Count binary strings of length n with no two adjacent 1s, tracking how many valid strings end in 0 and in 1. python def no11(n)…
- Problem: Find the minimum sum of a falling path through a square grid: start anywhere in the top row and move to one of the (up to) three…
- Problem: Minimum path sum from the top of a number triangle to the bottom (step to the same index or index + 1 in the next row), computed…
- Problem: Pairs (a, b) with a < b can be chained when the next pair's a is strictly greater than the previous b. Find the longest chain…