Pattern #58
Dijkstra's Algorithm
Important interview questions, cheapest-node-first thinking, min-heap relaxation, stale entries, path reconstruction, weighted-grid variants, and Go templates.
Must Solve
15 core questions — solve these first.
- 1.Network Delay TimeStandard adjacency-list Dijkstra from sourcemedium
- 2.Path With Minimum EffortDistance is minimum possible maximum edge effortmedium
- 3.Swim in Rising WaterMinimize the maximum elevation on the pathhard
- 4.Cheapest Flights Within K StopsState must include stops usedmedium
- 5.Number of Ways to Arrive at DestinationTrack distance and number of equal shortest pathsmedium
- 6.Minimum Cost to Reach DestinationHeap ordered by accumulated costmedium
- 7.Minimum Cost Path in a Weighted GridCells are nodes; moves carry costmedium
- 8.Reachable Nodes in Subdivided GraphDistances determine remaining moves on each edgehard
- 9.Path With Maximum ProbabilityUse a max heap and multiply probabilitiesmedium
- 10.Minimum Cost to Make at Least One Valid Path in a Grid0/1 weights; compare with 0-1 BFShard
- 11.Minimum Obstacle Removal to Reach CornerEntering an obstacle adds cost 1hard
- 12.Find the City With Smallest Number of NeighborsRun from each source or use Floyd-Warshallmedium
- 13.Minimum Weighted Subgraph With Required PathsCombine forward and reverse Dijkstra distanceshard
- 14.Second Minimum Time to Reach DestinationKeep two best arrival timeshard
- 15.Dijkstra Shortest Path with Path ReconstructionStore parent when distance improvesmedium
Also Important
7 more weighted shortest-path patterns.
- 16.Shortest Path in Weighted Undirected GraphAdd both directions to adjacency listmedium
- 17.Shortest Path in Weighted Directed GraphRespect edge directionmedium
- 18.Multi-Source DijkstraPush every source with distance 0medium
- 19.Dijkstra with Extra StateHeap contains cost plus complete statehard
- 20.Dijkstra on GridEncode cells or keep row and column in statemedium
- 21.Dijkstra with Time / ConstraintsTime or remaining resource changes the statehard
- 22.A* Search — Practical ExtensionDijkstra guided by an admissible heuristichard
How to Think
- Weighted shortest path and all weights non-negative?Dijkstra
- Main data structure?Min Heap / Priority Queue
- What does the heap store?(distance, node)
- What operation repeats?Relax outgoing edges
Take cheapest node
↓
Skip it if the heap entry is stale
↓
Relax neighbors
↓
Push every improvement
↓
RepeatGo Quick Reference — Core Dijkstra
The heap may contain multiple entries for one node. Process only the entry equal to the current best distance.
func dijkstra(n int, graph [][]Edge, start int) []int {
dist := make([]int, n)
for i := range dist { dist[i] = INF }
dist[start] = 0
pq := MinHeap{{dist: 0, node: start}}
for pq.Len() > 0 {
cur := heap.Pop(&pq).(State)
if cur.dist != dist[cur.node] { continue } // stale
for _, edge := range graph[cur.node] {
nextDist := cur.dist + edge.weight
if nextDist < dist[edge.to] {
dist[edge.to] = nextDist
heap.Push(&pq, State{nextDist, edge.to})
}
}
}
return dist
}- • Dijkstra is correct only when weights are non-negative.
- • Early exit is safe when the target is popped with its current best distance.
- • Do not mark visited when a node is merely discovered.
Variants & Path Reconstruction
Actual shortest path
On improvement:
parent[next] = node
Trace target → parent → start
Then reverse the sequence.Count shortest paths
better: ways[next] = ways[node]
equal: ways[next] += ways[node]Minimax Dijkstra
For Minimum Effort or Rising Water, combine the path using max(currentCost, edgeCost), then minimize that value.
Extra state
If stops, time, or resources change future options, heap state and distance keys must include them.
Heap top → cheapest known distance
Stale pop → skip
Better neighbor → update + push
Target popped → safe early exit
Negative edge → invalid algorithmComplexity
Adjacency list + binary heap
Time: O((V + E) log V)
Space: O(V + E)
Dense matrix implementation
Time: O(V²)Heap operations add the logarithmic factor; use 64-bit distances when path sums can exceed int range.
Common Interview Mistakes
- • Using Dijkstra with a negative edge
- • Using a FIFO queue instead of a min heap
- • Marking visited like BFS
- • Forgetting to skip stale heap entries
- • Reversing the heap order
- • Adding only one direction for an undirected edge
- • Overflowing distance sums or ignoring unreachable nodes
- • Tracking node only when the real state has extra constraints
Interview Rules
Non-negative weights → Dijkstra
Heap → (distance, node)
Pop → cheapest known state
Stale entry → skip
Better route → relax + push
Actual route → parent array
Extra constraint → extra state
Negative edge → Bellman-FordProduction Thinking
Network routing → minimize latency or routing cost from one origin.
Maps and logistics → weights represent time, distance, fuel, or toll.
Production warning → use int64 for large costs and skip stale heap entries.
Remember This
Dijkstra → non-negative weighted graph
Priority → total distance so far
Relaxation → newDist < dist[next]
Stale entry → poppedDist != dist[node]
Actual path → parent array
Time → O((V + E) log V)💡 Golden Rule: Always expand the currently cheapest valid state, then relax its outgoing edges.