progress

~/problems / Weighted graphs / Dijkstra (weighted shortest paths)

Shortest path with reconstruction

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

A directed graph has nodes 0 .. n-1 and edges (u, v, w) with non-negative weights. There may be self-loops and several edges between the same pair.

Write shortest_path(n, edges, src, dst) -> tuple: (distance, path) where distance is the length of a shortest path from src to dst and path is that path as a list of nodes [src, ..., dst]. If dst can't be reached, return (float("inf"), []). When src == dst the answer is (0, [src]).

If several shortest paths exist, return any one of them; the tests check that your path really uses edges of the graph and really costs distance.

edges = [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1), (2, 3, 5)]
shortest_path(5, edges, 0, 3)   # (4, [0, 2, 1, 3])
shortest_path(5, edges, 0, 4)   # (inf, [])
A weighted directed graph where the shortest route from 0 to 3 goes 0, 2, 1, 3 for a total of 4, cheaper than taking 0 to 1 directly (4 + 1) or 2 to 3 directly (1 + 5); node 4 is unreachable.

Constraints: 1 <= n <= 5 * 10^4, up to 2 * 10^5 edges, 0 <= w <= 10^4.

⭐ Bonus: a speed test with 50,000 nodes on a single long path earns a star in O((V + E) log V) without deep recursion.

Show hint

while computing distances with Dijkstra, remember for every node which node its current best distance came from, and update that whenever the distance improves. Then walk those links back from dst.

Topic: Dijkstra (weighted shortest paths). Heap of (dist, node), skip stale entries; non-negative weights only.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc