Problem 787 · LeetCode 787(opens in a new tab)
Cheapest Flights Within K Stops
MediumDynamic programming
There are n cities, numbered 0 to n − 1, and a list of one-way flights. Each entry of flights is [from, to, price]: a ticket from city from to city to for that price.
You start in city src and want to reach city dst. A stop is any city you land in on the way, other than the start and the end, and you may make at most k of them. Return the lowest total price of such a trip, or −1 if no trip fits.
Example 1
Input: n = 4, flights = [[0,1,50],[0,2,150],[1,3,300],[2,3,100],[1,2,40]],
src = 0, dst = 3, k = 1
Output: 250
Why: 0 → 2 → 3; the 190 route 0 → 1 → 2 → 3 needs 2 stops2 more examples and the constraints
Example 2
Input: the same flights, src = 0, dst = 3, k = 2 Output: 190 Why: with 2 stops allowed, 50 + 40 + 100 fits
Example 3
Input: the same flights, src = 0, dst = 3, k = 0 Output: -1 Why: no flight goes straight from 0 to 3
Constraints
- 2 ≤ n ≤ 100
- 0 ≤ number of flights ≤ n · (n − 1) / 2, with at most one flight from any city to any other
- 1 ≤ price ≤ 10,000
- 0 ≤ src, dst, k < n, and src ≠ dst
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every route (DFS)O(nᵏ)
- k + 1 rounds of relaxing (Bellman-Ford)O(k · E)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 cities and k = 99 | Verdict |
|---|---|---|---|
| Try every route (DFS) | O(nᵏ) | Explodes on dense graphs | |
| k + 1 rounds of relaxing | O(k · E) | Best; short and exact |
n = cities, E = flights, k = stops allowed.
Edge cases to test
- k = 0. Only a direct flight counts; Example 3 has none, so −1.
- No flights at all. Nothing leaves src, so the answer is −1.
- Cheaper but too long. The cheapest route overall may use too many stops; Example 1 must skip the 190 route.
- Cycles. Flights can loop back; the round count, not a visited set, keeps the search finite.
- dst unreachable. If cost[dst] is still infinity after all rounds, return −1.
Common mistakes
- Updating
costin place during a round, which lets one round chain several flights and breaks the stop limit. - Running k rounds instead of k + 1: k stops means k + 1 flights.
- Using plain Dijkstra with a visited set, which throws away a pricier route that has fewer stops.
How to talk through it
- 1Clarify. Do stops count the start and the end? Are flights one-way? Can there be cycles?
- 2Give the brute force. DFS over every route with at most k + 1 flights; say why it explodes.
- 3Reframe by flights used. After r rounds, cost holds the cheapest price with at most r flights, so k + 1 rounds answer the question.
- 4Code the rounds. Say why each round reads
costand writes a copy. - 5Test out loud. Run k = 0 and the cheaper-but-too-long route before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?