Data Structures & AlgorithmsVery hardProduct company OA

Tarjan's SCC algorithm, then the condensation DAG. What is printed (SCCs, source components, sink components, minimum edges to add to make the graph strongly connected)?

Tarjan's SCC algorithm, then the condensation DAG. What is printed (SCCs, source components, sink components, minimum edges to add to make the graph strongly connected)?
import sys
sys.setrecursionlimit(10000)
n = 8
g = {0: [1], 1: [2], 2: [0, 3], 3: [4], 4: [3], 5: [4, 6], 6: [], 7: [6]}
idx, low, on, st, comp, cnt, t = {}, {}, set(), [], {}, 0, 0
def dfs(u):
    global t, cnt
    idx[u] = low[u] = t; t += 1; st.append(u); on.add(u)
    for v in g[u]:
        if v not in idx: dfs(v); low[u] = min(low[u], low[v])
        elif v in on: low[u] = min(low[u], idx[v])
    if low[u] == idx[u]:
        while True:
            w = st.pop(); on.discard(w); comp[w] = cnt
            if w == u: break
        cnt += 1
for u in range(n):
    if u not in idx: dfs(u)
indeg, outdeg = [0] * cnt, [0] * cnt
for u in g:
    for v in g[u]:
        if comp[u] != comp[v]: outdeg[comp[u]] += 1; indeg[comp[v]] += 1
src = sum(1 for c in range(cnt) if indeg[c] == 0); snk = sum(1 for c in range(cnt) if outdeg[c] == 0)
print(cnt, src, snk, max(src, snk) if cnt > 1 else 0)
  1. A. 5 2 2 2
  2. B. 5 3 2 3
  3. C. 4 3 2 3
  4. D. 6 3 2 5

Correct answer: B. 5 3 2 3

SCCs: {0, 1, 2}, {3, 4}, {5}, {6}, {7}. In the condensation, {0, 1, 2}, {5}, {7} have no incoming edges (3 sources) and {3, 4}, {6} have no outgoing edges (2 sinks). For a condensation with more than one node, the minimum number of added edges is max(sources, sinks) = 3 – each source needs an incoming and each sink an outgoing edge, and one edge can serve a sink and a source together. 2 forgets that sources and sinks must both be fixed. O(V + E).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic