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

Exams that ask this topic