Data Structures & AlgorithmsHardProduct Company SDE pattern
Bellman–Ford from vertex 0 with a negative edge. What is printed (distances, and whether a negative cycle exists)?
Bellman–Ford from vertex 0 with a negative edge. What is printed (distances, and whether a negative cycle exists)?
edges = [(0, 1, 6), (0, 2, 7), (1, 2, 8), (1, 3, 5), (1, 4, -4), (2, 3, -3), (2, 4, 9), (3, 1, -2), (4, 0, 2), (4, 3, 7)]
n = 5; INF = float('inf'); d = [0] + [INF] * (n - 1)
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)
print(d, neg)- A. [0, 6, 7, 4, 2] False
- B. [0, 2, 7, 4, -2] True
- C. [0, 2, 7, 4, -2] False
- D. [0, 2, 7, 11, -2] False
Correct answer: C. [0, 2, 7, 4, -2] False
Relax every edge V − 1 = 4 times. 0 → 2 (7) → 3 (4) → 1 (2) → 4 (−2). A further pass that still improves a distance would mean a negative cycle; here none does. Dijkstra would finalise vertex 1 at 6 too early. O(VE).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What is printed? (detect a cycle in an undirected graph with union-find) python def hascycle(n, edges): p = list(range(n)) def f(x): while…
- What is printed? (number of paths from source to target in a DAG with memoisation) python from functools import lrucache g = {0: [1, 2…
- What is printed? (longest path in a DAG using topological order) python g = {'A': [('B', 3), ('C', 2)], 'B': [('D', 4)], 'C': [('D', 1)…
- What is printed? (unique paths count with memoised recursion vs closed form) python from functools import lrucache from math import comb…
- What is printed? (LIS length with O(n²) DP and the number of LIS) python a = [1, 3, 5, 4, 7] n = len(a); L = [1] n; C = [1] n for i in…
- What is printed? (coin change: number of combinations) python def ways(coins, amt): dp = [1] + [0] amt for c in coins: for a in range(c…