Data Structures & AlgorithmsEasyWipro · Accenture pattern

What is printed? (count connected components with DFS on an adjacency list)

What is printed? (count connected components with DFS on an adjacency list)
n = 8
edges = [(0, 1), (1, 2), (3, 4), (5, 6), (6, 7), (7, 5)]
g = [[] for _ in range(n)]
for u, v in edges: g[u].append(v); g[v].append(u)
seen = [False] * n; comps = 0; sizes = []
for s in range(n):
    if seen[s]: continue
    comps += 1; st = [s]; seen[s] = True; sz = 0
    while st:
        u = st.pop(); sz += 1
        for v in g[u]:
            if not seen[v]: seen[v] = True; st.append(v)
    sizes.append(sz)
print(comps, sizes)
  1. A. 4 [3, 2, 3]
  2. B. 3 [3, 2, 2]
  3. C. 2 [3, 5]
  4. D. 3 [3, 2, 3]

Correct answer: D. 3 [3, 2, 3]

Components {0,1,2}, {3,4}, {5,6,7}: three, of sizes 3, 2, 3. The triangle 5–6–7 is still one component. Iterative DFS with an explicit stack avoids recursion-depth limits. O(V + E).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic