Dijkstra's Algorithm

March 31, 2026
#dijkstra #shortest-path #graph #algorithms #data-structures #interviewing

Introduction

Dijkstra’s Algorithm finds the shortest path from a source vertex to all other vertices in a weighted graph with non-negative edge weights. It’s the algorithm behind GPS navigation, network routing, and any system that needs to find the cheapest path between two points.

The core idea: greedily pick the unvisited vertex with the smallest known distance, then update its neighbors’ distances. This is essentially BFS with a priority queue instead of a regular queue — the priority queue ensures we always process the closest vertex next.

You should be familiar with Graphs, Graph Representation, Heaps, and BFS before reading this.

How it works

Graph:
    A --4-- B
    |       |
    2       1
    |       |
    C --3-- D --5-- E

Find shortest paths from A:

Step 1: Start at A (dist=0). Update neighbors: B=4, C=2
Step 2: Visit C (dist=2). Update: D=2+3=5
Step 3: Visit B (dist=4). Update: D=min(5, 4+1)=5 (no change)
Step 4: Visit D (dist=5). Update: E=5+5=10
Step 5: Visit E (dist=10). Done.

Shortest distances from A: {A:0, B:4, C:2, D:5, E:10}

Implementation

Reconstructing the path

The prev map tracks how we reached each vertex. Walk it backwards to get the actual path:

function getPath(prev, target) {
  const path = [];
  let current = target;

  while (current !== null) {
    path.unshift(current);
    current = prev[current];
  }

  return path;
}

const { dist, prev } = dijkstra(graph, 'A');
console.log(getPath(prev, 'E'));  // ['A', 'C', 'D', 'E'] — wait, let's check
// Actually: A(0) → B(4) → D(5) → E(10), or A(0) → C(2) → D(5) → E(10)
// Both give distance 10, prev tracks whichever was found first

Why non-negative weights only?

Dijkstra’s greedy approach assumes that once a vertex is processed, its shortest distance is final. Negative weights break this:

A --1-- B
 \      |
  5    -4
   \    |
    → C ←

Dijkstra from A: processes B(1), then C(5).
But B→C = 1 + (-4) = -3, which is shorter than 5.
Dijkstra already finalized C=5 and misses this.

Complexity analysis

Implementation Time Space
Min-heap (binary) O((V + E) log V) O(V)
Unsorted array O(V²) O(V)
Fibonacci heap O(V log V + E) O(V)

The min-heap version is the standard choice. The unsorted array version is simpler but slower — it’s better only for very dense graphs where E ≈ V².

Dijkstra vs BFS

Dijkstra BFS
Edge weights Weighted (non-negative) Unweighted (or weight = 1)
Data structure Priority queue Queue
Time O((V + E) log V) O(V + E)
Use case Weighted shortest path Unweighted shortest path

BFS is a special case of Dijkstra where all weights are 1. If your graph is unweighted, use BFS — it’s simpler and faster.

Practice problems

  1. Network Delay Time (LeetCode 743)
  2. Cheapest Flights Within K Stops (LeetCode 787)
  3. Path with Minimum Effort (LeetCode 1631)
  4. Swim in Rising Water (LeetCode 778)
  5. Shortest Path in Binary Matrix (BFS variant)