Data Structures & AlgorithmsHardProduct Company SDE · graph round
Problem: Check whether the directed graph with edges 0->1, 1->2, 2->0, 2->3 contains a cycle using Kahn's algorithm (count the nodes that get processed). What is printed?
Problem: Check whether the directed graph with edges 0->1, 1->2, 2->0, 2->3 contains a cycle using Kahn's algorithm (count the nodes that get processed). What is printed?
from collections import deque
n = 4
edges = [(0, 1), (1, 2), (2, 0), (2, 3)]
g = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
g[u].append(v)
indeg[v] += 1
q = deque(i for i in range(n) if indeg[i] == 0)
done = 0
while q:
u = q.popleft()
done += 1
for v in g[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
print('cycle' if done < n else 'acyclic')What is printed?- A. acyclic
- B. 3
- C. cycle
- D. 4
Correct answer: C. cycle
Vertices 0, 1 and 2 form a directed cycle, so none of them ever reaches in-degree zero and done stays below 4, which the code reports as a cycle.
More Coding Interview Problems questions
- Problem: Find the minimum cost to reach node 3 from node 0 using at most 2 edges in the directed graph with edges (0,1,5), (1,3,5)…
- Problem: Count the nodes at depth exactly 2 in the rooted tree with children 0: [1, 2], 1: [3], 2: [4, 5], 3: [], 4: [], 5: []. Root 0 has…
- Problem: How many integers from 1 to 1000 are divisible by 3 or by 5 but not by both?
- Problem: What is the product of the distinct prime factors of 360? Run the code. python n = 360 p, prod = 2, 1 while p p <= n: if n % p ==…
- Problem: What is the sum of all primes up to 50? Run the code. python print(sum(p for p in range(2, 51) if all(p % d for d in range(2…
- Problem: What is C(20, 10) mod 1000? Compute it with Pascal's triangle reduced mod 1000. Run the code. python n, k = 20, 10 C = [[0] (k +…