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?- A. [0, 1, 2, 0, 3]
- B. [0, 1, 2, 3, 4]
- C. [0, 2, 1, 3]
- 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
- Problem: Print a matrix in spiral order (clockwise from the top-left). cpp vector<int> spiral(vector<vector<int>>& m) { vector<int> out…
- Problem: Rotate an n × n image 90° clockwise in place. python def rotate(m): n = len(m) for i in range(n): for j in range(i + 1, n)…
- Problem: Set the whole row and column to 0 for every 0 in a matrix. python def zeroes(m): R, C = len(m), len(m[0]) rows = {r for r in…
- Problem: Find the element that appears more than n/2 times (guaranteed to exist) using Boyer–Moore voting. java static int majority(int[]…
- Problem: Sort an array of 0s, 1s and 2s in one pass (Dutch national flag). cpp void sort012(vector<int>& a) { int lo = 0, mid = 0, hi =…
- Problem: Find the next lexicographic permutation of a digit list in place. python def nextperm(a): i = len(a) - 2 while i >= 0 and a[i] >=…