Cheapest Flights Within K Stops – Solution & Complexity
Solution Walkthrough
1. Bound the path length
- At most
kstops means at mostk + 1actual flight edges. - So you never need routes longer than
k + 1relaxations, even if the graph contains cycles.
2. Brute-force baseline
- Explore all routes from
srctodstwith DFS while tracking how many stops remain. - That works for tiny graphs, but the branching factor makes it explode quickly.
3. Layered Bellman-Ford relaxation
- Let
prices[v]mean the cheapest known cost to reach cityvusing at most the previous number of edges. - On each of
k + 1rounds, copy the current array and relax every directed flight into the copy. Using the copy is crucial: it prevents one round from chaining together more than one new edge. - After
k + 1rounds,prices[dst]is the best cost using at mostk + 1edges, exactly matching the stop limit.
4. Final solution (all languages)
A copied distance array per round enforces the stop budget while keeping the implementation compact.
5. Why the copied array matters
- If you relax into the same array you are reading from, one round might accidentally use two newly updated edges, violating the stop budget.
- Using
nextPricesguarantees roundronly represents routes with at mostredges. - This is the same core Bellman-Ford idea, just stopped early because the interview problem limits the route length.