Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: Count the strongly connected components and the number of edges in the condensation DAG (Kosaraju).

Problem: Count the strongly connected components and the number of edges in the condensation DAG (Kosaraju).
n = 8
E = [(0,1),(1,2),(2,0),(2,3),(3,4),(4,5),(5,3),(6,5),(6,7),(7,6)]
g = [[] for _ in range(n)]; rg = [[] for _ in range(n)]
for u, v in E: g[u].append(v); rg[v].append(u)
seen, order = [False] * n, []
def d1(u):
    seen[u] = True
    for v in g[u]:
        if not seen[v]: d1(v)
    order.append(u)
for u in range(n):
    if not seen[u]: d1(u)
comp = [-1] * n
def d2(u, c):
    comp[u] = c
    for v in rg[u]:
        if comp[v] == -1: d2(v, c)
c = 0
for u in reversed(order):
    if comp[u] == -1: d2(u, c); c += 1
dag = {(comp[u], comp[v]) for u, v in E if comp[u] != comp[v]}
print(c, len(dag))
What is printed?
  1. A. 3 3
  2. B. 3 2
  3. C. 4 2
  4. D. 2 1

Correct answer: B. 3 2

SCCs: {0, 1, 2}, {3, 4, 5}, {6, 7}. Edges between components are 2→3 and 6→5, i.e. {012} → {345} and {67} → {345}; using a set merges parallel component edges, so the DAG has 2 edges.

More Coding Interview Problems questions

Exams that ask this topic