Cheapest Flights Within K Stops

medium

There are n cities (0 .. n-1) connected by flights[i] = [from, to, price] (directed). Given src, dst, and k, return the cheapest price from src to dst using at most k stops (so at most k+1 flights), or -1 if there is no such route.

Hints

At most k stops means at most k+1 flights — bound the number of edges.
Run Bellman-Ford for exactly k+1 rounds.
Relax each round off the previous round's distances (a copy) so one round adds only one flight.

Common doubts

Relaxing in place could chain several flights in a single round, exceeding the stop limit; a snapshot ensures each round extends paths by exactly one edge.
Dijkstra minimises cost ignoring hop count, so it may pick a cheaper route with too many stops. You must track edges used.
k stops equals k+1 flights (the stops are the intermediate cities).

Interview follow-ups

Use a priority queue keyed by cost with state (city, stops used), allowing revisits with more remaining stops.
Bellman-Ford still works for bounded edges, but a negative cycle would make 'cheapest' unbounded without the stop limit.

Fun facts

  • LeetCode 787 — the flagship 'shortest path with a hop constraint' problem.
  • The copy-per-round trick is the crux; relaxing in place is the classic bug here.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
0→1→2 costs 200 with one stop, cheaper than the direct 500.
Example 2
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
With no stops, only the direct flight is allowed.
Constraints

- 1 <= n <= 100 - 0 <= flights.length <= n*(n-1) - 0 <= src, dst < n - 0 <= k < n - 1 <= price <= 10^4

Solve this problem →