Data Structures & AlgorithmsHardProduct company OA
Problem: Shortest paths from node 1 in a weighted DAG (negative edges allowed): topologically sort with Kahn's algorithm, then relax edges in that order.
Problem: Shortest paths from node 1 in a weighted DAG (negative edges allowed): topologically sort with Kahn's algorithm, then relax edges in that order.
from collections import deque
def dag_short(n, edges, src):
adj = [[] for _ in range(n)]; indeg = [0] * n
for u, v, w in edges: adj[u].append((v, w)); indeg[v] += 1
order = []; q = deque(i for i in range(n) if indeg[i] == 0)
while q:
u = q.popleft(); order.append(u)
for v, w in adj[u]:
indeg[v] -= 1
if indeg[v] == 0: q.append(v)
INF = float("inf"); d = [INF] * n; d[src] = 0
for u in order:
if d[u] < INF:
for v, w in adj[u]: d[v] = min(d[v], d[u] + w)
return d
print(dag_short(6, [(0, 1, 5), (0, 2, 3), (1, 3, 6), (1, 2, 2), (2, 4, 4), (2, 5, 2), (2, 3, 7), (3, 4, -1), (4, 5, -2)], 1))What is printed?- A. [inf, 0, 2, 9, 6, 4]
- B. [inf, 0, 2, 6, 5, 3]
- C. [5, 0, 2, 6, 5, 3]
- D. [inf, 0, 2, 6, 5, 4]
Correct answer: B. [inf, 0, 2, 6, 5, 3]
In topological order every predecessor of v is final before v is relaxed, so one pass suffices even with negative weights. From 1: d[2] = 2, d[3] = min(6, 2 + 7) = 6, d[4] = min(2 + 4, 6 − 1) = 5, d[5] = min(2 + 2, 5 − 2) = 3. Node 0 is upstream of 1, so it stays INF (edges are directed). O(V + E).
More Coding Interview Problems questions
- Problem: An investor starts with capital w and may finish at most k projects; project i needs capital[i] to start and adds profits[i] when…
- Problem: A single CPU receives tasks (enqueue time, duration). When idle it starts the available task with the shortest duration (ties…
- Problem: Walk along buildings of given heights; climbing up by d needs d bricks or one ladder (going down is free). Return the furthest…
- Problem: Find the smallest range [lo, hi] that contains at least one number from each of k sorted lists (min-heap of one pointer per list…
- Problem: Choose the root(s) that minimise the height of an unrooted tree. Repeatedly strip all current leaves; the last 1 or 2 nodes are…
- Problem: Count the strongly connected components of a directed graph with Kosaraju's algorithm (DFS finishing order, then DFS on the…