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?
  1. A. (3, [3, 3, 2])
  2. B. (4, [3, 3, 1, 1])
  3. C. (2, [5, 3])
  4. 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

Exams that ask this topic