Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the shortest travel time from node 0 to every node in a road network with non-negative weights.
Problem: Find the shortest travel time from node 0 to every node in a road network with non-negative weights.
import heapq
def dijkstra(n, edges, s):
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w)); adj[v].append((u, w))
dist = [float('inf')] * n; dist[s] = 0; pq = [(0, s)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]: continue
for v, w in adj[u]:
if d + w < dist[v]:
dist[v] = d + w; heapq.heappush(pq, (dist[v], v))
return dist
print(dijkstra(5, [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1), (2, 3, 5), (3, 4, 3)], 0))What is printed?- A. [0, 3, 1, 4, 7]
- B. [0, 4, 1, 5, 8]
- C. [0, 3, 1, 6, 9]
- D. [0, 3, 1, 4, 8]
Correct answer: A. [0, 3, 1, 4, 7]
0→2 (1), 2→1 (1 + 2 = 3, better than the direct 4), 1→3 (4, better than 2→3 = 6), 3→4 (7). The 'd > dist[u]' check skips stale heap entries. O((V + E) log V).
More Coding Interview Problems questions
- Problem: A network has V = 10⁵ routers and E = 2 × 10⁵ links with latencies that can be negative (but no negative cycle). Which…
- Problem: Union-find with path compression answers which friends are in the same circle. How many circles remain after the unions? python…
- Problem: Find the minimum total cost to connect all offices (minimum spanning tree) using Kruskal's algorithm. python def kruskal(n…
- Problem: Find the length of the shortest transformation from a start word to an end word, changing one letter at a time, every…
- Problem: Determine whether a graph can be coloured with two colours so that no edge joins equal colours (bipartite). python from…
- Problem: Count the number of shortest paths (fewest edges) from node 0 to node n − 1 in an unweighted graph. python from collections…