Print Shortest Path

medium

Given a weighted undirected graph with V vertices (0 .. V-1) and edges edges[i] = [u, v, w] (non-negative w), return the vertices of a minimum-weight path from source 0 to target V-1, in order. If several minimum-weight paths exist, choosing the smallest predecessor at each vertex makes the path deterministic. Return [-1] if V-1 is unreachable.

Hints

Run Dijkstra, but also record a parent for each vertex whenever you improve its distance.
Reconstruct the path by following parents from the target back to the source, then reverse.
Break ties toward the smaller predecessor so the path is unique.

Common doubts

parent[v] is the vertex that gave v its shortest distance, so parents form a shortest-path tree; walking it from the target reaches the source.
Multiple shortest paths may exist; a fixed rule makes the returned path deterministic (and identical for the scan and heap versions).
[-1] — the target has infinite distance and no parent chain to the source.

Interview follow-ups

Store all predecessors that achieve the shortest distance, then DFS the predecessor DAG.
No — use Bellman-Ford with parent tracking instead.

Fun facts

  • The parent array is precisely Dijkstra's shortest-path tree.
  • Navigation apps reconstruct routes exactly this way — distances plus back-pointers.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: V = 4, edges = [[0,1,1],[1,2,1],[0,2,2],[2,3,1]]
Output: [0, 2, 3]
0→2→3 has weight 3; 2's smaller predecessor 0 is chosen over 1.
Example 2
Input: V = 4, edges = [[0,1,2],[2,3,3]]
Output: [-1]
Vertex 3 is unreachable from 0.
Constraints

- 1 <= V <= 10^5 - 0 <= edges.length <= 10^5 - 1 <= w <= 10^9 - no negative weights

Solve this problem →