Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Run Bellman–Ford from node 0 on a directed graph with negative edges, then check for a negative cycle with one more relaxation pass.
Problem: Run Bellman–Ford from node 0 on a directed graph with negative edges, then check for a negative cycle with one more relaxation pass.
def bellman(n, edges, src):
INF = float("inf"); d = [INF] * n; d[src] = 0
for _ in range(n - 1):
for u, v, w in edges:
if d[u] + w < d[v]: d[v] = d[u] + w
neg = any(d[u] + w < d[v] for u, v, w in edges)
return d, neg
print(bellman(4, [(0, 1, 4), (0, 2, 5), (1, 3, -3), (2, 1, -2), (3, 2, 6)], 0), bellman(3, [(0, 1, 1), (1, 2, -2), (2, 1, 1)], 0)[1])What is printed?- A. ([0, 3, 5, 0], False) False
- B. ([0, 3, 5, 0], True) True
- C. ([0, 4, 5, 1], False) True
- D. ([0, 3, 5, 0], False) True
Correct answer: D. ([0, 3, 5, 0], False) True
Shortest paths: 0 → 2 = 5; 0 → 2 → 1 = 5 − 2 = 3 (better than the direct 4); 0 → 2 → 1 → 3 = 0. The cycle 1 → 3 → 2 → 1 weighs −3 + 6 − 2 = +1, so no negative cycle. In the second graph 1 → 2 → 1 weighs −1, so a further pass still relaxes → True. Dijkstra would settle node 1 at 4 too early. O(V·E).
More Coding Interview Problems questions
- Problem: All-pairs shortest paths with Floyd–Warshall on a 4-node directed graph (INF = no path). python INF = float("inf") def floyd(n…
- Problem: n computers and a list of cables; you may unplug any cable and reconnect it between any two computers. Minimum moves to connect…
- Problem: Given equations like "a==b" and "b!=c" over single-letter variables, can all hold at once? Union all '==' pairs first, then check…
- Problem: A 3-wheel lock starts at "000"; each move turns one wheel by ±1 (9 wraps to 0). Some codes are dead (the lock jams). Find the…
- Problem: Shortest paths from node 1 in a weighted DAG (negative edges allowed): topologically sort with Kahn's algorithm, then relax edges…
- 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…