Cheapest Flights Within K Stops Solution
Find the minimum cost from src to dst using at most k stops. The step limit is the key twist: the cheapest unrestricted route might use too many edges.
Problem Statement
A stop is an intermediate city, so a route with at most k stops can use at most k + 1 flight edges. We want the cheapest such route, or -1 if none exists.
DFS Over All Valid Routes β Exponential
We could recursively try every outgoing flight, tracking current cost and how many edges remain. Whenever we hit dst within the limit, update the answer.
Enumerating every route with at most k + 1 edges guarantees we eventually see the cheapest valid one.
k + 1 relaxation passes, not n - 1.Bellman-Ford Limited to K+1 Passes β O((K+1) Β· E)
Classic Bellman-Ford says that after i passes, we know the cheapest costs using at most i edges. So for this problem, we only need k + 1 passes. The subtle part is that each pass must read from the previous pass's distances, not the ones being updated right now.
- Initialize
dist[src] = 0; all others are infinity. - Repeat exactly
k + 1times. - At the start of each pass, clone the previous
distarray intonext. - Relax every flight
u β vusing the olddist[u]. - After the pass, replace
distwithnext.
- βCheapest / minimum cost with at most K stops / K edges / K movesβ usually means Bellman-Ford by number of edges, or a state-augmented Dijkstra.
- Bellman-Ford is often the cleanest interview answer here.
Visual Walkthrough
Trace src=0, dst=3, k=1.
Code β Java & Python
Complexity Analysis
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| DFS route enumeration | Exponential | O(k) recursion | Explores too many repeated route prefixes. |
| Bellman-Ford β optimal fit | O((K + 1) Β· E) | O(V) | Exactly matches the βat most K stopsβ constraint by limiting edge count. |
Edge Cases & Pitfalls
| Case | Expected behavior | Why it matters |
|---|---|---|
| No valid route within stop limit | Return -1 | The cheapest unrestricted route may still be invalid. |
k = 0 | Allow only direct flights | That means exactly one Bellman-Ford pass. |
| Cheaper route with too many stops | Ignore it | The constraint is part of the optimization problem. |
| Unreachable intermediate city | Skip its outgoing relaxations | Guard against adding to infinity. |
| In-place updates per pass | Wrong answer | One pass would accidentally use more than one newly unlocked edge. |
dist in-place during a pass. That breaks the βat most i edges after i passesβ invariant. Always write into a cloned array for the current pass.