Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE
Problem: Find the bug: Kahn's algorithm is used to schedule build steps, but nobody checks whether a cycle exists. What does it return for a graph with a cycle and for an acyclic one?
Problem: Find the bug: Kahn's algorithm is used to schedule build steps, but nobody checks whether a cycle exists. What does it return for a graph with a cycle and for an acyclic one?
from collections import deque
def topo(n, edges):
adj = [[] for _ in range(n)]; indeg = [0] * n
for u, v in edges: adj[u].append(v); indeg[v] += 1
q = deque(i for i in range(n) if indeg[i] == 0); order = []
while q:
u = q.popleft(); order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0: q.append(v)
return order
print(topo(5, [(0, 1), (1, 2), (2, 3), (3, 1), (0, 4)]), topo(4, [(3, 1), (2, 1), (1, 0)]))What is printed?- A. [0, 4] [2, 3, 1, 0]
- B. [0, 4, 1, 2, 3] [3, 2, 1, 0]
- C. [] [2, 3, 1, 0]
- D. [0, 1, 2, 3, 4] [2, 3, 1, 0]
Correct answer: A. [0, 4] [2, 3, 1, 0]
Nodes on the cycle 1 → 2 → 3 → 1 never reach in-degree 0, so they are silently missing: the order has 2 of 5 nodes. The fix is to report a cycle when len(order) < n. In the second graph both 2 and 3 start with in-degree 0 and are dequeued in index order, then 1, then 0. O(V + E).
More Coding Interview Problems questions
- Problem: n, q ≤ 2·10⁵ operations of two kinds: add v to every a[l..r], and ask for sum a[l..r]. A Fenwick tree with two arrays supports…
- Problem: For n = 2·10⁵, compute Σ over all subarrays of (max − min). Sum of maxima minus sum of minima, each via monotonic stacks with…
- Problem: Adjacent piles in a row are merged two at a time; merging costs the combined size. Minimise the total cost (interval DP over [i…
- Problem: Rain on a height grid flows to a neighbour with height ≤ the current cell. The west/north edge touches one sea, the east/south…
- Problem: A recursive routine splits a problem of size n into parts n/3 and 2n/3 and does n extra work: W(n) = W(n/3) + W(2n/3) + n. The…
- Problem: Find the bug: Dijkstra (finalising a node when it is popped) is run on a graph with one negative edge and compared with…