Dijkstra's Algorithm
Example
while (heap.size) {
const [d, u] = heap.pop();
for (const [v, w] of graph[u]) {
if (d + w < dist[v]) { dist[v] = d + w; heap.push([dist[v], v]); }
}
}while (heap.size) {
const [d, u] = heap.pop();
if (d > dist[u]) continue;
for (const [v, w] of graph[u]) {
if (d + w < dist[v]) { dist[v] = d + w; heap.push([dist[v], v]); }
}
}Skipping outdated heap entries stops the loop from expanding the same node again with a longer distance.
Common mistakes
- Running Dijkstra's algorithm on a graph with negative weights and getting wrong distances.
- Re-sorting the whole queue array each step and making it slow.
Key points
- The graph has no negative edge weights; with them the code uses Bellman-Ford instead.
- A min-heap priority queue is used, not an array sorted on every iteration.
- Stale heap entries are skipped when a popped distance is larger than the stored one.
Interview questions
Why doesn't Dijkstra's algorithm work with negative weights?
It finalizes a node once popped, assuming no later path can be cheaper. A negative edge can break that assumption.
Does JavaScript have a built-in priority queue for Dijkstra?
No, JavaScript has no built-in heap. Write a small binary heap or use a library.
What is the complexity of Dijkstra without a heap?
Scanning an array for the closest node gives O(V^2), which can be fine for dense graphs.
