Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Traverse a small directed graph (adjacency lists in the order shown) from node 0, once with recursive DFS and once with BFS.
Problem: Traverse a small directed graph (adjacency lists in the order shown) from node 0, once with recursive DFS and once with BFS.
from collections import deque
g = {0: [1, 2], 1: [3], 2: [3, 4], 3: [5], 4: [5], 5: []}
order, seen = [], set()
def dfs(u):
seen.add(u); order.append(u)
for v in g[u]:
if v not in seen: dfs(v)
dfs(0)
q, vis, bfs = deque([0]), {0}, []
while q:
u = q.popleft(); bfs.append(u)
for v in g[u]:
if v not in vis: vis.add(v); q.append(v)
print(order, bfs)What is printed?- A. [0, 1, 3, 5, 2, 4] [0, 1, 2, 3, 5, 4]
- B. [0, 2, 4, 5, 3, 1] [0, 1, 2, 3, 4, 5]
- C. [0, 1, 2, 3, 4, 5] [0, 1, 3, 5, 2, 4]
- D. [0, 1, 3, 5, 2, 4] [0, 1, 2, 3, 4, 5]
Correct answer: D. [0, 1, 3, 5, 2, 4] [0, 1, 2, 3, 4, 5]
DFS goes deep first: 0 → 1 → 3 → 5, backtracks to 0, then 2 → (3 already seen) → 4 (5 seen). BFS visits by distance: 0; 1, 2; 3, 4 (3 discovered from 1, 4 from 2); then 5. Both are O(V + E).
More Coding Interview Problems questions
- Problem: Values are pushed one by one into Python's heapq (a binary min-heap stored in a list), then one value is popped. python import…
- Problem: Each element of a log is at most k = 2 positions away from its sorted position. Sort it with a min-heap of size k + 1. python…
- Problem: Is an undirected graph with n nodes a tree? Check edge count = n − 1 and that union-find never sees an edge inside one component…
- Problem: Build a minimum spanning tree with Prim's algorithm (lazy heap of edges) starting from node 0; report the total weight and the…
- Problem: From index i of an array you may jump to i + a[i] or i − a[i] (staying inside). Can you reach any index holding 0? (BFS.) python…
- Problem: Paint-bucket fill: recolour the 4-connected region of the start cell's colour and report how many cells changed. python def…