Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Clone check – count how many nodes a BFS reaches from node 0 in a directed graph that contains a cycle.

Problem: Clone check – count how many nodes a BFS reaches from node 0 in a directed graph that contains a cycle.
from collections import deque
adj = {0: [1, 2], 1: [2], 2: [0, 3], 3: [3], 4: [0]}
seen, q, order = {0}, deque([0]), []
while q:
    u = q.popleft(); order.append(u)
    for v in adj[u]:
        if v not in seen:
            seen.add(v); q.append(v)
print(order)
What is printed?
  1. A. [0, 1, 2, 0, 3]
  2. B. [0, 1, 2, 3, 4]
  3. C. [0, 2, 1, 3]
  4. D. [0, 1, 2, 3]

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

The visited set stops the cycle 0 → 2 → 0 and the self-loop on 3 from re-queuing nodes. Node 4 points INTO 0 but is not reachable from 0. BFS order follows adjacency order level by level. O(V + E).

More Coding Interview Problems questions

Exams that ask this topic