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?- A. 3 3
- B. 3 2
- C. 4 2
- 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
- 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…
- Problem: Maximum profit from at most 2 buy-sell transactions (sell before buying again). python def two(p): b1 = b2 = float('-inf'); s1 =…