Shortest paths and Dijkstra
Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.
What you will be able to do
#- Distinguish unweighted shortest paths from weighted ones.
- Run Dijkstra's algorithm with a min-heap and relaxation.
- Explain why Dijkstra requires non-negative edge weights.
Overview
#What shortest means
In an unweighted graph the shortest path is the one with the fewest edges, and BFS finds it. In a weighted graph each edge has a cost and the shortest path minimises total cost, which can have more edges than another route.
Dijkstra's algorithm
Dijkstra grows a set of vertices whose shortest distance is finalised.
- Set the start distance to 0 and all others to infinity.
- Put the start in a min-heap keyed by distance.
- Repeatedly pop the vertex with the smallest tentative distance.
- For each neighbour, relax the edge: if going through the current vertex is cheaper, update the neighbour's distance and push it.
function dijkstra(graph, start) {
const dist = new Map();
for (const node of Object.keys(graph)) dist.set(node, Infinity);
dist.set(start, 0);
const heap = [[0, start]];
while (heap.length) {
heap.sort((a, b) => a[0] - b[0]);
const [d, node] = heap.shift();
if (d > dist.get(node)) continue;
for (const [next, weight] of graph[node] || []) {
if (!dist.has(next)) dist.set(next, Infinity);
const candidate = d + weight;
if (candidate < dist.get(next)) {
dist.set(next, candidate);
heap.push([candidate, next]);
}
}
}
return dist;
}
The d > dist.get(node) check discards stale heap entries. With a real binary heap the cost is O((vertices + edges) log vertices); the array sort above is a simpler but slower stand-in.
Why non-negative weights
Dijkstra finalises a vertex when it is popped, assuming no later path can be cheaper. A negative edge could make a later path cheaper, breaking that assumption. Negative weights need Bellman-Ford, which relaxes every edge repeatedly.
Choosing the algorithm
Unweighted: BFS. Non-negative weights: Dijkstra. Negative weights without negative cycles: Bellman-Ford. All-pairs: Floyd-Warshall. State the assumption you are relying on before you pick.
Practice next
- Find the cheapest route with at most k stops.
- Explain why Bellman-Ford can handle negative edges but Dijkstra cannot.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
With edges A->B weight 1, A->C weight 4, B->C weight 1, what is the shortest distance from A to C?
starter.javascript// relax edges from A, then from BReveal the reference answer
reference.javascriptThe direct edge costs 4, but A to B to C costs 1 + 1 = 2. Dijkstra updates C to 2 when it relaxes B, so the shortest distance is 2.Authored expected output: 2
A more expensive direct edge can be beaten by a cheaper two-edge route.
Exercise 2Explain
Explain why Dijkstra can fail when an edge has a negative weight.
Reveal the reference answer
reference.textDijkstra finalises a vertex's distance when it is popped, assuming no future path can be cheaper. A negative edge can make a later route cheaper than the finalised distance, so the algorithm would return a wrong answer. Bellman-Ford avoids this by relaxing all edges repeatedly instead of finalising early.Authored expected output: A negative edge can beat a finalised distance, invalidating the early-finalise assumption.
The correctness of Dijkstra rests on non-negative weights.
Exercise 3Explain
Explain why the stale-entry check d > dist.get(node) is needed when using a heap.
Reveal the reference answer
reference.textWhen a vertex's distance improves, a new entry is pushed but the old entry remains in the heap. When the old entry is later popped, its stored distance is larger than the current best, so the check skips it. Without the check the algorithm would redo work with outdated distances.Authored expected output: Old heap entries hold outdated distances and must be skipped.
This lazy-deletion trick keeps the heap simple without a decrease-key operation.
Common misconceptions
#- BFS finds shortest paths in a weighted graph. It only does so when all weights are equal.
- Dijkstra works with negative edges. Negative weights break the finalise-on-pop assumption.
- The first path found to a vertex is always optimal. Only after popping the vertex is its distance final.
Follow-up practice
#- dsa-from-zero-dynamic-programming
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.