Data Structures & AlgorithmsHardTCS CodeVita · Microsoft SDE OA

On vertices 0..4 a weighted directed graph has these edges, stored in the order shown in the code: (3→4, −2), (2→4, 8), (4→1, 2), (1→3, 6), (2→3, 4), (1→2, −3), (0→2, 5), (0→1, 4). It has no negative cycle. Run Bellman–Ford from source 0 with the standard V−1 rounds, relaxing edges in storage order. What distance is printed for vertex 4?

On vertices 0..4 a weighted directed graph has these edges, stored in the order shown in the code: (3→4, −2), (2→4, 8), (4→1, 2), (1→3, 6), (2→3, 4), (1→2, −3), (0→2, 5), (0→1, 4). It has no negative cycle. Run Bellman–Ford from source 0 with the standard V−1 rounds, relaxing edges in storage order. What distance is printed for vertex 4?
E=[(3,4,-2),(2,4,8),(4,1,2),(1,3,6),(2,3,4),(1,2,-3),(0,2,5),(0,1,4)]
INF=10**9; d=[INF]*5; d[0]=0
for _ in range(4):
    for u,v,w in E:
        if d[u]<INF and d[u]+w<d[v]: d[v]=d[u]+w
print(d[4])
What is printed?
  1. A. 7
  2. B. 13
  3. C. -2
  4. D. 3

Correct answer: D. 3

After V−1 = 4 rounds of relaxing every edge the shortest path 0→1→2→3→4 with weight 4−3+4−2 = 3 is found. Stopping after two or three rounds misses the long chain, and starting every node at 0 invents cheap paths.

More Coding Interview Problems questions

Exams that ask this topic