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?- A. 7
- B. 13
- C. -2
- 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
- A task graph has six nodes 0 to 5 and dependencies 5→0, 4→0, 4→1, 5→2, 2→3, 3→1 (an edge u→v means u must finish before v). Among all…
- Eight vertices 0..7 receive the edges (0,1), (2,3), (4,5), (1,2), (5,6) in that order in a disjoint-set structure with union by size and…
- Compute the sum over all subarrays of the minimum element, for a = [3, 1, 2, 1, 3]. Subarrays are counted by position, so equal values in…
- Find the sum of the maximum of every window of length 3 in a = [1, 3, −1, −3, 5, 3, 6, 7] (windows slide one step at a time). python…
- In the reflected binary Gray code, the number with index i is i XOR (i >> 1). Using 0-based indices, what is the value printed for i = 5…
- How many binary strings of length 30 contain neither the substring "11" nor the substring "000"? python n=30 dp={('0',1):1,('1',1):1} for…