Bellman-Ford
O(V · E)
Relax every edge V−1 times; the k-stops variant just caps the number of relaxation rounds at k+1.
0%
mastery
0/5 solved
0/5 solved
Recognise it
The signal
Shortest path with negative edge weights, detect a negative cycle, or cheapest path using at most K edges / stops.
1Brute force
Enumerate paths.
2The observation
Exponential path enumeration: dynamic programming over number of edges.
3Why it works
After round i, dist[v] <= the shortest path to v using at most i edges.
Reach for it when
- +detect a negative (or positive, for longest path) cycle
- +at most K edges / stops
Not when
- ×Large graph, all weights non-negativeuse Dijkstra, O(E log V)
- ×All-pairs distances on small Vuse Floyd-Warshall
Practice
0/5 solved
- Network Delay TimeFoundationFoundationAmazon, UberMedium
- Cheapest Flights Within K StopsApply it · Limit on edges used.Apply itAmazon, UberMedium
- Cycle FindingTwists · Find and print a negative cycle.TwistsCSESMedium
- High ScoreMastery checkMastery checkCSESMedium
- Subarray Sum ConstraintsCSESHard
Pitfalls
Classic bugs
- !K-stops: relax from a copy of last round's dist, or one round chains several edges and breaks the limit.
- !A negative cycle only ruins the answer if it's reachable from the source and can reach the target; check, don't reject all.
Looks like it, isn't
- Path with Maximum Probability needs Dijkstra (Weighted Shortest Path)
Why
Multiplying probabilities <= 1 never increases a path's value, so Dijkstra with a max-heap is valid. source ↗