Cheapest Flights Within K Stops
MediumNeetCode 150 Advanced GraphsStripeProblem
There are n cities numbered 0 to n − 1. Each entry of flights is
[from, to, price]: a one-way flight with that price.
Starting in city src, find the cheapest way to reach city dst using at most
k stops. A stop is a city you land in and leave again, so the trip has at most k + 1
flights. Return the lowest total price, or -1 if there is no such trip.
Constraints
- 1 ≤ n ≤ 100
- 0 ≤ flights.length ≤ n · (n − 1) / 2
- flights[i] = [from, to, price] with from ≠ to, and each pair (from, to) appears at most once
- 1 ≤ price ≤ 10⁴
- 0 ≤ src, dst, k < n and src ≠ dst
Examples: pick one to animate
Solutions
Time: There are k + 1 rounds, and each round looks at every flight once.
Space: Two price arrays of n cities are kept, and the flights are only read.
Let prices[c] be the cheapest cost to reach city c using at most r flights. Start with r = 0: only
the source costs 0. Each round allows one more flight: copy the array, then for every flight
from → to try prices[from] + price against the copy's to. Reading the old
array and writing the copy matters: otherwise one round could chain several flights and break the stop limit.
After k + 1 rounds the answer is prices[dst]. The sentinel 1000000 is larger than any real price:
a route has at most 99 flights of at most 10000 each.