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)- A. 4 [3, 2, 3]
- B. 3 [3, 2, 2]
- C. 2 [3, 5]
- 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).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Floyd–Warshall on 4 vertices. What is the shortest distance from 0 to 3, and from 3 to 1? python INF = float('inf') d = [[0, 3, INF, 7]…
- Bellman–Ford from vertex 0 with a negative edge. What is printed (distances, and whether a negative cycle exists)? python edges = [(0, 1…
- What is printed? (detect a cycle in an undirected graph with union-find) python def hascycle(n, edges): p = list(range(n)) def f(x): while…
- What is printed? (number of paths from source to target in a DAG with memoisation) python from functools import lrucache g = {0: [1, 2…
- What is printed? (longest path in a DAG using topological order) python g = {'A': [('B', 3), ('C', 2)], 'B': [('D', 4)], 'C': [('D', 1)…
- What is printed? (unique paths count with memoised recursion vs closed form) python from functools import lrucache from math import comb…