Shortest Path Algorithms
Cheapest routes in weighted graphs - Dijkstra, Bellman-Ford and 0-1 BFS.
- waiting / queued
- active this step
- current
- visited / done
- result
- removed / popped
Start at A
A costs 0 and is the only entry in the heap.
VARIABLES
- settled
- -
- dist
- {A: 0}
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
Dijkstra repeatedly settles the closest unsettled node using a min-heap and needs non-negative weights. Bellman-Ford handles negative weights by relaxing every edge up to V − 1 times.
Why it matters
Routing, network delay and cheapest-flight problems need the minimum total weight, not the fewest edges.
Think of it like this
Planning a road trip by always extending the route to the nearest town you haven’t finalized yet.
Use it when
- Weighted edges with non-negative costs (Dijkstra)
- Negative edges, or a limit on edges used (Bellman-Ford)
- Weights of only 0 or 1 (0-1 BFS with a deque)
Avoid it when
- Unweighted graphs - plain BFS is simpler
- Negative weights with Dijkstra - it can finalize nodes too early
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Dijkstra with a binary heap | O((V + E) log V) | O(V + E) |
| Bellman-Ford | O(V × E) | O(V) |
| 0-1 BFS | O(V + E) | O(V) |
Often confused with: BFS - it minimizes the number of edges; Dijkstra minimizes total weight.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- “At most k stops” suggests Bellman-Ford limited to k + 1 rounds
- Skip stale heap entries whose distance is worse than the best known
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Using Dijkstra when some edge weights are negative
- Not skipping stale heap entries - wasted work
- Treating a node as final when it’s pushed rather than when it’s popped
Edge cases to test
- Unreachable nodes - report infinity or -1
- Several edges between the same pair
- Zero-weight edges
Knowledge check
Quick check to lock in the intuition.
Why can Dijkstra give wrong answers with negative edge weights?
Practice
Apply what you just watched on real interview problems.