InterviewPrepKit

Home / Coding / Advanced Graphs

Cheapest Flights Within K Stops

medium Original β†—
Solving tips
  • Shortest path with a 'at most k stops' budget means plain Dijkstra fails, because the cheapest way into a city may use too many edges to continue.
  • Reframe 'k stops' as 'k+1 edges' and run exactly k+1 rounds of Bellman-Ford, reading the cost at dst.
  • Critical pitfall: relax each round against a snapshot (copy) of the previous distances, or a single round chains multiple edges and overshoots the budget.
  • Target O(k*E) time and O(n) space; alternatively expand Dijkstra's state to (city, edges-used).

Problem

There are n cities numbered 0 to n - 1, connected by directed flights. Each flight is given as [u, v, price]: you can fly from city u to city v for price dollars.

Given a start city src, a destination dst, and an integer k, return the cheapest total price to travel from src to dst using at most k intermediate stops β€” i.e. a route of at most k + 1 flights. If no such route exists, return -1.

The catch: the globally cheapest route may use too many stops, so plain shortest-path logic is not enough.

Examples

  • n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 β†’ 700 β€” the cheaper route 0β†’1β†’2β†’3 (cost 400) needs 2 stops, so we must take 0β†’1β†’3.
  • Same graph with k = 2 β†’ 400 β€” now 0β†’1β†’2β†’3 is allowed.
  • n = 3, flights = [[0,1,100],[1,2,100]], src = 0, dst = 2, k = 0 β†’ -1 β€” reaching city 2 requires stopping at city 1.

Constraints

  • 1 <= n <= 100
  • 0 <= len(flights) <= n * (n - 1), no duplicate edges
  • 1 <= price <= 10^4
  • 0 <= k < n, src != dst

Think about it first

Hint 1 "At most k stops" means "at most k + 1 edges". Rephrase the question as: what is the cheapest path from src to dst that uses at most k + 1 edges?
Hint 2 Why does ordinary Dijkstra fail here? Because the cheapest way to reach an intermediate city may burn too many edges to continue to dst. You need to track cost per number of edges used, not just per city.
Hint 3 Bellman-Ford relaxes every edge once per round, and after r rounds it has found the cheapest paths using at most r edges. Run exactly k + 1 rounds β€” relaxing against a snapshot of the previous round so a single round can't chain two new edges β€” and read off the answer at dst.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.