Dijkstra's Algorithm

medium

Given a weighted undirected graph with V vertices (0 .. V-1), edges edges[i] = [u, v, w] with non-negative weight w, return the shortest distance from source vertex 0 to every vertex, or -1 if unreachable.

Hints

Repeatedly settle the closest unsettled vertex — its distance is final with non-negative weights.
Relax the settled vertex's edges to improve neighbours' distances.
Use a min-heap to fetch the closest vertex in O(log V).

Common doubts

The greedy 'closest is final' step fails with negative edges, since a later negative edge could shorten an already-settled path.
A vertex can be pushed several times as its distance improves; when popped with an outdated (larger) distance, skip it.
The O(V²) scan is fine for dense graphs; the heap's O((V+E) log V) wins when edges are sparse.

Interview follow-ups

Store a parent whenever you relax an improving edge, then backtrack from each vertex.
Use Bellman-Ford, which handles negatives (and detects negative cycles) at O(V·E).

Fun facts

  • Dijkstra devised this in 1956 — reportedly in about twenty minutes at a café.
  • With a Fibonacci heap it improves to O(E + V log V).

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: V = 4, edges = [[0,1,1],[0,2,4],[1,2,1],[2,3,1]]
Output: [0, 1, 2, 3]
0→1→2→3 gives 0,1,2,3 (0→2 direct of 4 is beaten by 0→1→2 = 2).
Example 2
Input: V = 4, edges = [[0,1,2],[2,3,3]]
Output: [0, 2, -1, -1]
Vertices 2 and 3 are unreachable from 0.
Constraints

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

Solve this problem →