The home where you level up

Save my spot

Dijkstra's Algorithm

Term side of the Card.
Topic: Graph Algorithms
Unit title: Dijkstra's Algorithm
Categories: Algorithm
Explanation side of the Card

Explanation: 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).

Example

Wrongjs
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]); }
  }
}
Rightjs
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.

The home where you level up

Daily 3-minute lessons to understand your AI's code.

No spam — just launch news.
Unsubscribe anytime. · Privacy Policy

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy