GRAPHS / ALGORITHM BRIEF

Dijkstra's algorithm

Dijkstra's algorithm finds the shortest path from one source to every other node in a graph with non-negative edge weights.

IntermediatePhase 05 / Topic 6 of 10Mental modelComplexityEdge cases
01

Overview

Dijkstra's algorithm finds the shortest path from one source to every other node in a graph with non-negative edge weights. It repeatedly takes the unvisited node with the smallest known distance, finalizes it, and relaxes its outgoing edges (tries to improve neighbors' distances through it).

A min-heap keyed by distance makes this O((V + E) log V). The greedy choice is safe because with non-negative weights, no later path can ever be shorter than the current smallest distance. With negative edges that guarantee breaks, and you need Bellman-Ford instead.

Water spreading through pipes

Pour water into the source. It reaches the nearest junction first, then spreads from there. The order in which junctions get wet is exactly the order Dijkstra finalizes them: by shortest travel time from the source.

02

When to use it

  • Shortest path or minimum cost with non-negative weights.
  • Network delay, travel time, cheapest route, minimum effort.
  • Grid problems where moves have different costs.
  • State-space search where each state has a cost (Dijkstra on (node, extra state)).
03

Problem patterns it solves

Single-source shortest time

Recognize it when: time for a signal to reach all nodes.

  • 743. Network Delay Time
  • 1976. Number of Ways to Arrive at Destination
Minimize the maximum edge (bottleneck)

Recognize it when: minimize the largest step or effort along a path.

  • 1631. Path With Minimum Effort
  • 778. Swim in Rising Water
Maximize probability

Recognize it when: multiply probabilities; use a max-heap.

  • 1514. Path with Maximum Probability
Dijkstra with extra state

Recognize it when: node plus stops used, fuel, or keys collected.

  • 787. Cheapest Flights Within K Stops
  • 1293. Shortest Path in a Grid with Obstacles Elimination
  • 2093. Minimum Cost to Reach City With Discounts
Grid with weighted moves

Recognize it when: cells have costs or moves cost differently.

  • 1368. Minimum Cost to Make at Least One Valid Path
  • 2290. Minimum Obstacle Removal to Reach Corner
04

Where it is used in real software

Navigation apps

Google Maps and Waze use Dijkstra-based algorithms (with A* heuristics and precomputed contraction hierarchies) over road networks with travel-time weights.

Internet routing

Link-state routing protocols such as OSPF and IS-IS run Dijkstra on each router to build forwarding tables.

Games

Pathfinding for units across terrain with different movement costs uses Dijkstra or A*.

Logistics

Delivery routing finds the cheapest or fastest route between warehouses and customers.

05

Key terms

dist[v]
Best known distance from the source to v.
Relaxation
If dist[u] + w < dist[v], update dist[v] and push it to the heap.
Finalized
When a node is popped with its current distance, that distance is optimal.
Stale entry
A heap entry whose distance is larger than dist[v]; skip it.
06

How it works, step by step

  1. 1
    Initialize

    dist[source] = 0 and all others Infinity. Push [0, source] to a min-heap.

  2. 2
    Pop the smallest distance

    Take [d, u] from the heap.

  3. 3
    Skip stale entries

    If d > dist[u], a better path was already found; continue.

  4. 4
    Relax each edge u -> v with weight w

    If d + w < dist[v], set dist[v] = d + w and push [dist[v], v].

  5. 5
    Repeat until the heap is empty

    Or stop early when the target is popped.

07

Shortest distances from A

Edges: A-B 4, A-C 1, C-B 2, B-D 1, C-D 5

Step 1 / 6
PopRelaxationsdist A, B, C, DHeap after
A (0)B = 4, C = 10, 4, 1, inf[C1, B4]
C (1)B: 1 + 2 = 3 < 4, D: 1 + 5 = 60, 3, 1, 6[B3, B4, D6]
B (3)D: 3 + 1 = 4 < 60, 3, 1, 4[B4, D4, D6]
B (4)stale, skip0, 3, 1, 4[D4, D6]
D (4)-0, 3, 1, 4[D6]
D (6)stale, skip0, 3, 1, 4[]

NOWPop: A (0) | Relaxations: B = 4, C = 1 | dist A, B, C, D: 0, 4, 1, inf | Heap after: [C1, B4]

The shortest path to D is A -> C -> B -> D with cost 4, even though the direct-looking edges suggested 5 or 6. Stale heap entries are how the simple version handles updated distances without a decrease-key operation.

08

Implementation

// Uses the PriorityQueue class from the Heap guidefunction dijkstra(n, edges, source) {  const graph = Array.from({ length: n }, () => []);  for (const [u, v, w] of edges) graph[u].push([v, w]);   const dist = new Array(n).fill(Infinity);  dist[source] = 0;  const heap = new PriorityQueue((a, b) => a[0] - b[0]);  heap.push([0, source]);   while (heap.size) {    const [d, u] = heap.pop();    if (d > dist[u]) continue; // stale entry    for (const [v, w] of graph[u]) {      if (d + w < dist[v]) {        dist[v] = d + w;        heap.push([dist[v], v]);      }    }  }  return dist;} // 743. Network Delay Time (1-indexed nodes)function networkDelayTime(times, n, k) {  const dist = dijkstra(n + 1, times, k).slice(1);  const worst = Math.max(...dist);  return worst === Infinity ? -1 : worst;}
09

Complexity and performance

With binary heapO((V + E) log V)

Standard implementation.

With array scanO(V^2)

Better for very dense graphs.

SpaceO(V + E)

Graph, distances, heap.

GridO(RC log RC)

Each cell is a node.

10

Trade-offs

Dijkstra vs BFS

If every edge has the same weight, BFS is simpler and O(V + E). With weights 0 and 1 only, 0-1 BFS with a deque is also O(V + E).

Dijkstra vs Bellman-Ford

Dijkstra is much faster but fails with negative weights. Bellman-Ford handles negatives and detects negative cycles in O(V x E).

Dijkstra vs A*

A* adds a heuristic estimate of the remaining distance to reach one target faster; with a zero heuristic it is Dijkstra.

11

Variants and related techniques

Path reconstruction

Store parent[v] = u when relaxing; walk back from the target.

Counting shortest paths

When d + w === dist[v], add ways[u] to ways[v].

Multi-source

Push every source at distance 0 at the start.

Bidirectional Dijkstra

Search from both ends and stop when they meet; used in road networks.

12

Common mistakes

  • Using Dijkstra with negative edges.

    Fix: Its greedy finalization becomes wrong; use Bellman-Ford or SPFA.

  • Not skipping stale entries.

    Fix: Check if (d > dist[u]) continue, or the algorithm does extra work and may give wrong counts.

  • Marking visited when pushing.

    Fix: A node's distance is only final when popped.

  • Integer overflow when adding weights in Java.

    Fix: Skip nodes with MAX_VALUE distance, or use long.

13

Interview questions

Why does Dijkstra fail with negative weights?

It finalizes a node when it is popped, assuming no later path can be cheaper. A negative edge discovered later could make an already-finalized distance smaller.

How would you solve Cheapest Flights Within K Stops?

Run Dijkstra (or Bellman-Ford for k + 1 rounds) on states (city, stops used), because the cheapest path might use too many stops and a pricier path with fewer stops can be the valid answer.

14

Practice problems

ProblemDifficultyWhat it trains
743. Network Delay TimeMediumCore template.
1514. Path with Maximum ProbabilityMediumMax-heap on products.
1631. Path With Minimum EffortMediumBottleneck distance.
787. Cheapest Flights Within K StopsMediumExtra state.
1976. Number of Ways to Arrive at DestinationMediumCounting shortest paths.
778. Swim in Rising WaterHardMinimize the maximum.