# Dijkstra's Algorithm

> The Dijkstra's Algorithm computes the shortest path from a source node to all other nodes in a graph with non-negative weights.

## How does Dijkstra's algorithm find the shortest path?

The shortest-path algorithm that finds the minimum distance from a starting node to all other nodes in a graph with non-negative weights. With a binary-heap priority queue it runs in O((V + E) log V).

- Topic: Graph Algorithms
- Type: algorithm

## Example

Wrong:

```js
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]); }
  }
}
```

Right:

```js
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.

## Related cards

- [Bellman-Ford Algorithm](https://wonderium.dev/algorithms/bellman-ford-algorithm.md)
- [Min Heap](https://wonderium.dev/algorithms/min-heap.md)
- [Weighted Graph](https://wonderium.dev/algorithms/weighted-graph.md)
- [Greedy Algorithms](https://wonderium.dev/algorithms/greedy-algorithms.md)
- [Breadth-First Search](https://wonderium.dev/algorithms/breadth-first-search.md)

---

- Level: [Algorithms](https://wonderium.dev/algorithms.md)
- HTML version: https://wonderium.dev/algorithms/dijkstra-algorithm
- Last updated: 2026-11-25
