Skip to main content

DSAPath15 minintermediate

Dijkstra vs Bellman-Ford

Dijkstra is faster for nonnegative weights; Bellman-Ford handles negative edges and detects reachable negative cycles.

DifficultyIntermediate
TierTier 1
ModuleComparisons
LanguagesPython

Why This Matters

Shortest-path bugs often come from using Dijkstra on a graph that violates its assumptions. The edge-weight condition is not a detail; it is the proof.

Decision Rule

Use Dijkstra when all edge weights are nonnegative. Use Bellman-Ford when negative edges may appear or when the task asks whether a reachable negative cycle exists.

Comparison Table

FeatureDijkstraBellman-Ford
Edge weightsrequires nonnegative weightsallows negative weights
Negative cycle detectionnoyes, if reachable from source
Common complexityO((V + E) log V) with heapO(VE)
Core operationextract minimum then relax outgoing edgesrelax every edge repeatedly
Best userouting with nonnegative costsarbitrage-style cycles, constraint systems

Worked Example

Suppose edges are S -> A = 2, S -> B = 5, and B -> A = -10. Dijkstra can settle A too early at distance 2, then later discover a better path S -> B -> A = -5.

Bellman-Ford repeatedly relaxes all edges, so it can correct earlier distance estimates and then run one extra pass to detect a reachable negative cycle.

Common Mistakes

MistakeCorrection
Thinking Dijkstra works with "only a few" negative edges.One negative edge can break the settled-distance invariant.
Using Bellman-Ford when all weights are nonnegative and performance matters.Dijkstra is usually the better fit.
Treating a negative edge as a negative cycle.A negative cycle is a cycle whose total weight is negative.

Diagnostic Questions

QuestionAnswer signal
Which algorithm detects reachable negative cycles?Bellman-Ford.
Why is Dijkstra faster on many sparse graphs?The heap extracts the next best frontier vertex efficiently.
What assumption makes Dijkstra's settled set valid?Nonnegative edge weights.

Exercises

  • Beginner: Choose the algorithm for a road map with positive distances.
  • Beginner: Choose the algorithm for currency exchange with possible arbitrage.
  • Beginner: Explain why negative cycle means no finite shortest path.
  • Intermediate: Build a tiny graph where Dijkstra fails because of a negative edge.
  • Intermediate: Implement Bellman-Ford negative-cycle detection.
  • Challenge: Explain how difference constraints reduce to shortest paths with Bellman-Ford.

References