Simple Algorithm
Algorithms & Data Structures · Optimal · 30 min

Dijkstra’s Algorithm in Depth

The proof, heap choices, universal optimality and breaking the sorting barrier.

Since Fibonacci heaps arrived in 1987, Dijkstra's algorithm in O(m+nlog⁡n)O(m + n\log n) looked like the last word on shortest paths with non-negative weights, because it outputs the vertices sorted by distance and sorting costs nlog⁡nn\log n. In 2024 it was proved universally optimal for exactly that task. In 2025, an algorithm that refuses to sort beat it on sparse directed graphs.

What you’ll learn

  • Prove Dijkstra's algorithm correct with a two-part invariant, and locate the single place where non-negative weights are needed.
  • Analyze Dijkstra's algorithm with arrays and with binary, dd-ary, Fibonacci, bucket and radix heaps, stating each bound with its model.
  • Prove the Ω(nlog⁡n)\Omega(n\log n) lower bound for ordering vertices by distance, and state the universal optimality theorem of Haeupler, Hladík, Rozhoň, Tarjan and Tětek (2024).
  • Explain how Duan, Mao, Mao, Shu and Yin (2025) beat O(m+nlog⁡n)O(m + n\log n) on sparse directed graphs without contradicting that lower bound, and how bidirectional search and preprocessing speed up road-network queries.

The invariant, precisely

DerivationProof that each step preserves the invariant
  1. len(P)  ≥  len(Ps→y)  ≥  d[y]  ≥  d[u]\text{len}(P) \;\ge\; \text{len}(P_{s \to y}) \;\ge\; d[y] \;\ge\; d[u]

    The minimum is exact. Let u∉Su \notin S minimize d[u]d[u], and let PP be any path from ss to uu. Its first vertex outside SS is some yy; the prefix up to yy has all earlier vertices in SS, so by (b) it is at least d[y]≥d[u]d[y] \ge d[u]. The rest of PP, from yy to uu, has non-negative length: this is the only place where w≥0w \ge 0 is used.

  2. d[u]=δ(s,u)d[u] = \delta(s, u)

    Every path to uu is at least d[u]d[u], and d[u]d[u] is the length of a real path, so (a) holds once uu joins SS:

  3. δS∪{u}(s,v)=min⁡(d[v], d[u]+w(u,v))\delta_{S \cup \{u\}}(s, v) = \min\big(d[v],\ d[u] + w(u, v)\big)

    (b) is restored by relaxing uu's edges. A shortest path to v∉S∪{u}v \notin S \cup \{u\} with earlier vertices in S∪{u}S \cup \{u\} either avoids uu, with length d[v]d[v], or can be taken to end with the edge u→vu \to v: if it went on from uu to a settled vertex xx, its prefix up to xx could be replaced by a shortest path to xx inside SS, which is no longer. So

  4. δ(s,u1)≤δ(s,u2)≤⋯≤δ(s,un)\delta(s, u_1) \le \delta(s, u_2) \le \cdots \le \delta(s, u_n)

    Settling order. After the step, every unsettled estimate is still at least d[u]d[u], since relaxing from uu adds w≥0w \ge 0. So the vertices are settled in nondecreasing order of distance: Dijkstra's algorithm also sorts the vertices by distance.

Zero-weight edges are fine, since the proof needs only w≥0w \ge 0, and ties may be broken arbitrarily. The last step matters later: an algorithm that settles vertices one at a time in distance order solves the distance order problem, and that problem has a lower bound.

Check your understanding

Where exactly does the correctness proof use the fact that all weights are non-negative?

  1. To bound the number of heap entries by m+1m + 1
  2. To show that the part of a path after it first leaves the settled set has length at least 00
  3. To guarantee that every vertex is reachable from ss
  4. To make the result independent of how ties are broken
Show the answer

B. To show that the part of a path after it first leaves the settled set has length at least 00

The minimum d[u]d[u] is exact because any path to uu first leaves SS at some yy with d[y]≥d[u]d[y] \ge d[u], and what follows cannot be negative. A negative edge after yy breaks exactly this step, which is how the counterexamples in the Optimized lesson work.

Heaps: the price of a priority queue

Dijkstra's algorithm makes nn insertions and extract-mins and up to mm decrease-keys (or mm extra insertions with lazy deletion). Its running time is therefore n⋅Textract+m⋅Tdecreasen \cdot T_{\text{extract}} + m \cdot T_{\text{decrease}}, and the choice of priority queue decides everything:

QueueDijkstra's running timeNotes
unsorted arrayO(n2)O(n^2)Dijkstra's original 1959 version; best on dense graphs
binary heapO((n+m)log⁡n)O((n + m)\log n)lazy deletion instead of decrease-key keeps the same bound
dd-ary heap, d≈m/nd \approx m/nO(mlog⁡m/nn)O(m \log_{m/n} n)Johnson (1975); linear once m≥n1+εm \ge n^{1 + \varepsilon}
Fibonacci heapO(m+nlog⁡n)O(m + n\log n)amortized O(1)O(1) decrease-key (Fredman & Tarjan, 1987)
bucket queue, integer weights ≤C\le CO(m+nC)O(m + nC)Dial (1969)
radix heap, integer weights ≤C\le CO(m+nlog⁡C)O(m + n\log C); O(m+nlog⁡C)O(m + n\sqrt{\log C}) combined with a Fibonacci heapAhuja, Mehlhorn, Orlin & Tarjan (1990)
Thorup's hierarchy, undirected graphs, integer weightsO(m)O(m)Thorup (1999), on the word RAM; it avoids visiting vertices in distance order
Comparison-based bounds hold for real weights; the bucket, radix and Thorup bounds need integer weights and operations on machine words.
DerivationTuning a d-ary heap
  1. Tdecrease=O(log⁡dn),Textract=O(dlog⁡dn)T_{\text{decrease}} = O(\log_d n), \qquad T_{\text{extract}} = O(d \log_d n)

    In a dd-ary heap, sift-up climbs log⁡dn\log_d n levels, while sift-down compares up to dd children per level:

  2. O((nd+m)log⁡dn)O\big((n d + m)\log_d n\big)

    So Dijkstra's algorithm costs

  3. O(mlog⁡m/nn)=O(m/ε)O\big(m \log_{m/n} n\big) = O(m / \varepsilon)

    Choosing d=max⁡(2,⌈m/n⌉)d = \max(2, \lceil m/n \rceil) balances the two terms. If m=n1+εm = n^{1 + \varepsilon}, then log⁡m/nn=1/ε\log_{m/n} n = 1/\varepsilon and the algorithm is linear for fixed ε\varepsilon:

Predict before you look

A graph has n=104n = 10^4 vertices and m=106m = 10^6 edges. With a dd-ary heap and d=m/n=100d = m/n = 100, how many levels can a decrease-key climb at most, that is, what is log⁡dn\log_d n?

Show the answer

2

log⁡100104=2\log_{100} 10^4 = 2, against about 13.313.3 levels in a binary heap. Each extract-min now scans up to 100100 children on each of 22 levels, but there are only n=104n = 10^4 of them: about 4×1064 \times 10^6 heap steps in total, against roughly 1.3×1071.3 \times 10^7 with a binary heap.

In practice, a binary heap with lazy deletion is hard to beat: Fibonacci heaps pay large constant factors for their O(1)O(1) decrease-key, and on integer weights, bucket and radix structures are popular. The Fibonacci bound matters for theory, where O(m+nlog⁡n)O(m + n\log n) became the benchmark to beat.

The sorting barrier and universal optimality

DerivationProof
  1. δ(s,vi)=xi  ⟹  distance order=sorted order of x1,…,xn\delta(s, v_i) = x_i \;\Longrightarrow\; \text{distance order} = \text{sorted order of } x_1, \dots, x_n

    Take a star: edges s→vis \to v_i of weight xix_i for i=1,…,ni = 1, \dots, n. Then δ(s,vi)=xi\delta(s, v_i) = x_i, and the distance order is the sorted order of the weights:

  2. 2depth≥n!  ⟹  depth≥⌈log⁡2n!⌉2^{\text{depth}} \ge n! \;\Longrightarrow\; \text{depth} \ge \lceil \log_2 n! \rceil

    With distinct weights, all n!n! orders are possible answers. An algorithm whose tests have two outcomes is a binary decision tree with a leaf for every answer it can give:

  3. log⁡2n!=nlog⁡2n−nlog⁡2e+O(log⁡n)\log_2 n! = n\log_2 n - n\log_2 e + O(\log n)

    By Stirling's formula:

Predict before you look

For a star with 1,0241{,}024 leaves, at least how many comparisons must a comparison-based algorithm make in the worst case to output the vertices in distance order?

Show the answer

8770

⌈log⁡21024!⌉=8,770\lceil \log_2 1024! \rceil = 8{,}770, since log⁡21024!≈8,769.01\log_2 1024! \approx 8{,}769.01. Stirling's first two terms give 10,240−1,024log⁡2e≈8,762.710{,}240 - 1{,}024\log_2 e \approx 8{,}762.7, and the O(log⁡n)O(\log n) term supplies the rest. So O(m+nlog⁡n)O(m + n\log n) is optimal for distance ordering on the worst graphs.

The intuition: on a path, each vertex is inserted and extracted before the next one arrives, so the working-set bound charges O(1)O(1) per vertex, which is linear time, as it must be since the order is forced. On a star, nn items wait in the heap together and each costs log⁡n\log n, matching sorting. The theorem says that Dijkstra's algorithm adapts this way on every graph.

Breaking the sorting barrier. Duan, Mao, Mao, Shu and Yin (STOC 2025, best paper) gave a deterministic O(mlog⁡2/3n)O(m\log^{2/3} n)-time algorithm for single-source shortest paths in directed graphs with real non-negative weights, in the comparison-addition model. It beats O(m+nlog⁡n)O(m + n\log n) whenever m=o(nlog⁡1/3n)m = o(n\log^{1/3} n), that is, on sparse graphs. Instead of extracting every vertex from a priority queue, it splits the problem recursively and runs a few rounds of Bellman–Ford-style relaxation to single out a small set of "pivot" vertices; only those need to be ordered, so the algorithm never sorts all vertices by distance. For undirected graphs, Duan, Mao, Shu and Yin (FOCS 2023) had already broken the bound with a randomized O(mlog⁡n⋅log⁡log⁡n)O(m\sqrt{\log n \cdot \log\log n}) algorithm. Follow-up work has improved these results further.

Check your understanding

Dijkstra's algorithm is universally optimal (2024), yet a 2025 algorithm runs faster on sparse directed graphs. Why is there no contradiction?

  1. The 2025 algorithm works only on undirected graphs
  2. The 2025 algorithm is randomized and fast only in expectation
  3. Universal optimality concerns outputting the vertices in distance order, which needs Ω(nlog⁡n)\Omega(n\log n) on some graphs; the 2025 algorithm computes the distances without sorting them
  4. Universal optimality holds only for integer weights
Show the answer

C. Universal optimality concerns outputting the vertices in distance order, which needs Ω(nlog⁡n)\Omega(n\log n) on some graphs; the 2025 algorithm computes the distances without sorting them

The two results solve different problems. Ordering the vertices by distance is as hard as sorting on a star, and Dijkstra's algorithm is optimal for it on every graph. Computing the distances themselves does not require sorting them, and that is the gap the 2025 algorithm exploits.

Road networks: bidirectional search and preprocessing

A navigation query asks for one pair (s,t)(s, t) on a graph with tens of millions of vertices. Plain Dijkstra settles every vertex closer to ss than tt is, roughly a disk around ss. Bidirectional Dijkstra grows two smaller disks instead, one forward from ss and one backward from tt along reversed edges, and must stop at the right moment.

DerivationProof sketch
  1. δ(s,v)<topforδ(v,t)<topb\delta(s, v) < \text{top}_f \quad\text{or}\quad \delta(v, t) < \text{top}_b

    Suppose a shortest path PP were shorter than μ≤topf+topb\mu \le \text{top}_f + \text{top}_b. Every vertex vv on PP has δ(s,v)+δ(v,t)=len(P)\delta(s, v) + \delta(v, t) = \text{len}(P), so one of the two terms is below its queue's top, and vv has been settled by that search:

  2. μ≤δ(s,x)+w(x,y)+δ(y,t)=len(P),a contradiction.\mu \le \delta(s, x) + w(x, y) + \delta(y, t) = \text{len}(P),\quad\text{a contradiction.}

    So every vertex of PP is settled by one search or the other, and some edge x→yx \to y of PP joins a vertex settled forward to one settled backward (if one search covers all of PP, its last edge into tt or first edge out of ss does). Scanning that edge set

Real routing engines go much further by preprocessing the graph once. ALT (Goldberg & Harrelson, 2005) runs A* with lower bounds derived, through the triangle inequality, from precomputed distances to and from a few landmark vertices. Contraction hierarchies (Geisberger, Sanders, Schultes & Delling, 2008) rank the vertices by importance and contract them one by one, adding a shortcut edge whenever a removed vertex was the only shortest connection between two neighbors; a query then runs a bidirectional Dijkstra that only climbs to more important vertices, and it settles a tiny fraction of the graph. Such techniques answer continental road queries orders of magnitude faster than plain Dijkstra.

Key takeaways

  • Invariant: settled distances are exact, and every unsettled estimate is the best path through settled vertices. Non-negativity is used once, to bound the part of a path after it leaves the settled set, and vertices are settled in nondecreasing distance.
  • Running time is nn extract-mins plus mm decrease-keys: O(n2)O(n^2) with an array, O((n+m)log⁡n)O((n + m)\log n) with a binary heap, O(mlog⁡m/nn)O(m\log_{m/n} n) with a dd-ary heap, O(m+nlog⁡n)O(m + n\log n) with a Fibonacci heap; integer weights allow buckets, radix heaps and, for undirected graphs, Thorup's O(m)O(m).
  • Ordering vertices by distance needs Ω(nlog⁡n)\Omega(n\log n) comparisons on a star, and Dijkstra's algorithm with a working-set heap is universally optimal for that task (Haeupler et al., FOCS 2024).
  • Distances alone can be computed faster than sorting: O(mlog⁡2/3n)O(m\log^{2/3} n) deterministically for directed graphs with real non-negative weights (Duan et al., STOC 2025).
  • Bidirectional Dijkstra stops when the two smallest keys add up to at least the best path seen; road-network engines add landmarks and contraction hierarchies on top.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Does Dijkstra's algorithm stay correct when some edges have weight exactly 00?

  1. Yes: the proof needs only that every weight is at least 00
  2. No: zero-weight edges create ties that break the invariant
  3. Only if the zero-weight edges form no cycle
  4. Only with a Fibonacci heap
Show the answer

A. Yes: the proof needs only that every weight is at least 00

The single use of the weights is "the rest of a path has length ≥0\ge 0", which zero-weight edges satisfy. Ties may be broken arbitrarily, and a cycle of zero-weight edges is harmless.

Question 2

Which arity dd makes Dijkstra's algorithm with a dd-ary heap run in O(mlog⁡m/nn)O(m \log_{m/n} n)?

  1. d=2d = 2
  2. d=log⁡nd = \log n
  3. d≈m/nd \approx m / n
  4. d=nd = n
Show the answer

C. d≈m/nd \approx m / n

The cost is O((nd+m)log⁡dn)O((nd + m)\log_d n): nn extract-mins at O(dlog⁡dn)O(d\log_d n) and mm decrease-keys at O(log⁡dn)O(\log_d n). Taking d≈m/nd \approx m/n makes nd≈mnd \approx m and gives O(mlog⁡m/nn)O(m\log_{m/n} n), which is linear when m≥n1+εm \ge n^{1 + \varepsilon}.

Question 3

Why must every comparison-based algorithm that outputs the vertices in order of distance make Ω(nlog⁡n)\Omega(n\log n) comparisons on some graphs?

  1. Because every vertex must be inserted into a heap
  2. Because on a star whose edges from ss have arbitrary weights, the distance order is the sorted order of those weights, and sorting needs ⌈log⁡2n!⌉\lceil \log_2 n! \rceil comparisons
  3. Because the graph has m≥nlog⁡nm \ge n \log n edges
  4. Because relaxing an edge costs log⁡n\log n time
Show the answer

B. Because on a star whose edges from ss have arbitrary weights, the distance order is the sorted order of those weights, and sorting needs ⌈log⁡2n!⌉\lceil \log_2 n! \rceil comparisons

On the star, δ(s,vi)=xi\delta(s, v_i) = x_i, so the output is a sorted list of the xix_i. A decision tree that distinguishes all n!n! orders has depth at least log⁡2n!=nlog⁡2n−O(n)\log_2 n! = n\log_2 n - O(n), whatever two-outcome tests it uses.

Question 4

Bidirectional Dijkstra searches forward from ss and backward from tt, and keeps μ\mu, the shortest ss–tt path seen so far through an edge between the two searches. Which stopping rule is correct while still stopping early?

  1. Stop when some vertex has been settled by both searches, and return the sum of its two distances
  2. Stop when the backward search first reaches ss
  3. Stop when the smallest keys of the two queues add up to at least μ\mu, and return μ\mu
  4. Alternate the two searches and stop after n/2n/2 steps each
Show the answer

C. Stop when the smallest keys of the two queues add up to at least μ\mu, and return μ\mu

Any ss–tt path shorter than μ\mu would consist of vertices settled by one search or the other, joined by an edge between the two settled regions, and scanning that edge would already have made μ\mu that small. The rule "stop at the first doubly settled vertex" fails: with s→ms \to m 4, m→tm \to t 4 and s→ts \to t 7, both searches settle mm first, giving 8 instead of 7.

Further reading

  • M. L. Fredman & R. E. Tarjan, "Fibonacci heaps and their uses in improved network optimization algorithms," Journal of the ACM 34(3) (1987), 596–615.
  • M. Thorup, "Undirected single-source shortest paths with positive integer weights in linear time," Journal of the ACM 46(3) (1999), 362–394.
  • B. Haeupler, R. Hladík, V. Rozhoň, R. E. Tarjan & J. Tětek, "Universal Optimality of Dijkstra via Beyond-Worst-Case Heaps," FOCS (2024).
  • R. Duan, J. Mao, X. Mao, X. Shu & L. Yin, "Breaking the Sorting Barrier for Directed Single-Source Shortest Paths," STOC (2025).
  • R. Geisberger, P. Sanders, D. Schultes & D. Delling, "Contraction Hierarchies: Faster and Simpler Hierarchical Routing in Road Networks," WEA 2008, LNCS 5038, 319–333.