Dijkstra's Algorithm
How Dijkstra's algorithm finds the cheapest route in a weighted graph with a min-heap, its variants and limits, and what interviewers ask about it.
On this page
Dijkstra's algorithm finds the cheapest path from one start node to every other node in a graph whose edges have non-negative costs. You use it when the cost of a route is the sum of its edge weights, such as travel time, distance or price, and you need the route with the lowest total.
BFS cannot do this, because it finds the route with the fewest edges and ignores weights. In the example graph traced below, the route A, B, E, F has 3 roads and takes 6 + 5 + 2 = 13 minutes, while A, C, B, D, E, F has 5 roads and takes only 2 + 3 + 2 + 1 + 2 = 10 minutes.
How Dijkstra's algorithm works
The algorithm keeps a best-known distance for every node. The start has distance 0, and every other node has infinity, which means no route has been found yet. It then repeats two steps until no unfinished node with a finite distance remains.
- Settle the unfinished node with the smallest known distance. Its distance is now final.
- Relax each road leaving that node. If going through the settled node gives a neighbour a smaller distance than the neighbour's current one, lower the neighbour's distance.
The smallest distance can be trusted because of the following argument. Suppose C is the closest unfinished node, at distance 2. Any other route to C must leave the settled region through some other unfinished node, and each of those is already at least 2 away. Because roads cannot have negative cost, the rest of that route can only add to the total, so nothing beats 2.
To find the smallest unfinished distance quickly, the algorithm keeps (distance, node) pairs in a min-heap.
A traced example
In the trace, the number next to each node is its best-known distance, and the settled nodes are the ones already marked. Watch B, which first gets distance 6 and later gets the better distance 5, leaving an out-of-date entry in the heap.
dist[start] = 0; push (0, start)while heap is not empty: (d, node) = pop smallest if d > dist[node]: skip (stale) for each (next, w) of node's roads: if d + w < dist[next]: dist[next] = d + w push (d + w, next)- heap (smallest first)00 A
1The start A gets distance 0 and every other place gets infinity. The heap holds one entry,
0 A. - heap (smallest first)02 C16 B
- popped
- 0 A
2The heap pops A with distance 0, so A is final. A's roads give B a distance of 0 + 6 = 6 and C a distance of 0 + 2 = 2, and both are pushed.
- heap (smallest first)05 B16 B29 D
- popped
- 2 C
3The heap pops C with distance 2, so C is final. Going through C reaches B at 2 + 3 = 5, which beats 6, and reaches D at 2 + 7 = 9. The old entry
6 Bstays in the heap and is now out of date. - heap (smallest first)06 B17 D29 D310 E
- popped
- 5 B
4The heap pops B with distance 5, so B is final. Going through B reaches D at 5 + 2 = 7, which beats 9, and reaches E at 5 + 5 = 10.
- heap (smallest first)07 D19 D210 E
- popped
- 6 B (stale)
5The heap pops
6 B. B is already final at 5 and 6 is larger, so this entry is stale and the loop skips it. - heap (smallest first)08 E19 D210 E312 F
- popped
- 7 D
6The heap pops D with distance 7, so D is final. Going through D reaches E at 7 + 1 = 8, which beats 10, and reaches F at 7 + 5 = 12.
- heap (smallest first)09 D110 E210 F312 F
- popped
- 8 E
7The heap pops E with distance 8, so E is final. Going through E reaches F at 8 + 2 = 10, which beats 12.
- heap (smallest first)010 F112 F
- popped
- 9 D, 10 E (stale)
8The heap pops
9 Dand then10 E. Both places are already final with smaller distances, so both entries are stale and are skipped. - heap (smallest first)012 F
- popped
- 10 F
9The heap pops F with distance 10, so F is final. Its roads lead only to places that are already final.
- heap (smallest first)
- F
- 10
- A → B → E → F
- 13
10The last entry,
12 F, is stale, and then the heap is empty. Following the parents back from F gives A, C, B, D, E, F, which has 5 roads and costs 10 minutes. The route with the fewest roads, A, B, E, F, costs 13.
Stale heap entries
When B's distance dropped from 6 to 5, the entry 6 B was already in the heap. A binary heap cannot cheaply find and change an entry in the middle, so the code pushes a new entry 5 B and leaves the old one in place.
The smaller entry comes out first, so B is settled at 5. When 6 B comes out later, the check d > dist[node] notices that it is out of date and skips it. In the trace, 4 of the 10 pops were stale. This costs a little extra work and saves the code from needing a heap that supports changing a priority.
The code
The graph is an adjacency list in which each neighbour is stored together with the cost of its road. In JavaScript, copy heapPush and heapPop from the heaps lesson and compare the first item of each pair, so that heap[parent] <= heap[i] becomes heap[parent][0] <= heap[i][0]. Python's heapq already orders tuples by their first item.
// graph: { A: [["B", 6], ["C", 2]], ... } place -> list of [neighbour, cost]
// Every place needs a list, even an empty one.
// heapPush / heapPop: the min-heap from the heaps lesson, comparing item[0]
function dijkstra(graph, start) {
const dist = { [start]: 0 };
const parent = { [start]: null };
const heap = [[0, start]]; // [distance so far, place]
while (heap.length > 0) {
const [d, node] = heapPop(heap);
if (d > dist[node]) continue; // stale entry: a shorter route was found
for (const [next, cost] of graph[node]) {
const newDist = d + cost;
if (!(next in dist) || newDist < dist[next]) {
dist[next] = newDist;
parent[next] = node;
heapPush(heap, [newDist, next]);
}
}
}
return { dist, parent };
}
// dijkstra(graph, "A").dist → { A: 0, B: 5, C: 2, D: 7, E: 8, F: 10 }import heapq
# graph: {"A": [("B", 6), ("C", 2)], ...} place -> list of (neighbour, cost)
# Every place needs a list, even an empty one.
def dijkstra(graph, start):
dist = {start: 0}
parent = {start: None}
heap = [(0, start)] # (distance so far, place)
while heap:
d, node = heapq.heappop(heap)
if d > dist[node]:
continue # stale entry: a shorter route was found
for nxt, cost in graph[node]:
new_dist = d + cost
if nxt not in dist or new_dist < dist[nxt]:
dist[nxt] = new_dist
parent[nxt] = node
heapq.heappush(heap, (new_dist, nxt))
return dist, parent
# dijkstra(graph, "A")[0] → {'A': 0, 'B': 5, 'C': 2, 'D': 7, 'E': 8, 'F': 10}A node that is missing from dist at the end is unreachable from the start. To recover the route itself, follow parent from the goal back to the start, as in BFS.
Every road can push one heap entry, so the heap holds at most about E entries. Each push and pop costs O(log E), which is O(log V) because E is at most V². The adjacency list and the heap take O(V + E) space.
Variants and when Dijkstra does not apply
Stopping early for a single target
If you need the distance to one goal only, return as soon as the goal is popped from the heap. That is the moment its distance becomes final, and the nodes that would have been settled afterwards are all farther away, so the search never visits them.
Dense graphs without a heap
Instead of a heap, you can store distances in an array and find the smallest unfinished one by scanning the whole array on each round. That takes O(V²) time. When the graph is dense, meaning E is close to V², this beats O((V + E) log V), and the code is shorter. For sparse graphs, which are the usual case, the heap version is faster.
Weights of only 0 and 1
When every edge costs either 0 or 1, a double-ended queue replaces the heap. After relaxing an edge of cost 0, you push the neighbour on the front of the queue, and after an edge of cost 1 you push it on the back. This is called 0-1 BFS and runs in O(V + E).
Decrease-key instead of stale entries
Some heap implementations support a decrease-key operation, which lowers the priority of an entry that is already in the heap. With it, the heap never holds more than V entries and no stale entries appear. A Fibonacci heap does this in constant amortised time and gives O(E + V log V), but in practice the simple binary heap with stale entries is almost always as fast and much easier to write, so it is the version to use in an interview.
Grids
When the input is a grid, each cell is a node and each of its four neighbours is a road whose cost is the value of the cell you move into, or whatever the problem defines. You do not build an adjacency list. You generate the neighbours inside the loop, and the heap holds (distance, row, column).
Unweighted graphs
If all edges cost the same, BFS already gives the cheapest route in O(V + E), and Dijkstra only adds the cost of a heap.
Negative edge costs
Dijkstra does not work when an edge can have a negative cost. The argument for settling the smallest distance first assumes that roads only add cost, and a negative road lets a later detour beat a node that was already settled. Use Bellman-Ford for that case.
A* search
A* is Dijkstra with one change: the heap key is the distance travelled so far plus an estimate of the remaining distance to the goal. A good estimate, such as straight-line distance on a map, makes the search head toward the goal instead of spreading out in every direction. The estimate must never be larger than the true remaining cost, or the result may not be the cheapest route.
Pitfalls
In the interview
The signal for Dijkstra is a graph, a grid or a network where moving along an edge has a cost and the problem asks for the minimum total cost, time or effort between two points. Typical phrasings are the cheapest flight with connections, the fastest time for a signal to reach every node, or the path through a grid with the smallest total effort. If all moves cost the same, the intended answer is BFS, and if costs can be negative, it is Bellman-Ford. Say which of these you are assuming before you start coding.
Questions to expect:
- "Why does Dijkstra fail with negative edges?" It marks a node final when it is popped, on the assumption that no later route can be cheaper. A negative edge breaks that assumption, because a longer route can end with a large negative cost and beat the settled distance. Bellman-Ford handles this by relaxing every edge repeatedly instead of trusting the smallest distance.
- "What is the time complexity, and why?" It is O((V + E) log V). Each edge can push at most one entry into the heap, and each push and pop costs O(log V), so the heap work is O(E log V), and the V pops add the rest.
- "How would you return the actual path?" Store the previous node each time a distance improves, which is the
parentmap in the code. After the search, start at the goal and follow the parents back to the start, then reverse the list. - "How do you detect a node that cannot be reached?" A node that was never given a distance, or that still has infinity at the end, is unreachable. Report that case explicitly instead of returning infinity as if it were a cost.
- "Can you make it faster for one source and one target?" Stop when the target is popped. If you can estimate the remaining distance, use A*. Searching from the start and from the goal at the same time, and stopping when the two searches meet, also reduces the nodes visited.
- "What if the graph is dense?" Replace the heap with an array scan to get O(V²), which is better than O(E log V) when E is close to V².
The heap holds (4, X), (7, Y) and (9, X), and dist[X] is 4. What happens when (9, X) is popped?
Why is BFS not enough when roads have different costs?
A graph has 1,000 nodes and 5,000 edges. Roughly how many basic heap steps does Dijkstra need?
A graph has some edges with negative cost. Which algorithm should you use for shortest paths from one start node?
What to practise next
For negative costs, or for distances between every pair of nodes, continue with Bellman-Ford and Floyd-Warshall. Prim's algorithm in Minimum Spanning Trees uses the same heap loop with a different key.