Cheapest Flights Within K Stops
Medium
Topics
There are n cities labelled 0 to n - 1 and a list of flights, where each row is [from, to, price]. Flights are one-way.
Return the cheapest price to travel from city 0 to city n - 1 using at most k stops, or -1 if no such route exists. A stop is an intermediate city, so k = 1 allows a route of up to two flights.
LeetCode passes src and dst as separate arguments. Here they are fixed at 0 and n - 1, which keeps the problem the same while fitting the three arguments the judge supplies. Those are named times, n and k by the harness: the flights table, the city count, and the stop limit.
Example 1
0 and must reach city 3, and k = 1 permits at most 1 intermediate city, so a route is legal only when it uses at most 2 flights. The thickened arrows are the cheapest legal route at 700; a route costing only 400 exists but needs more flights than the limit allows, so the stop limit and not the price decides the answer.Input: flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], n = 4, k = 1 Output: 700 Explanation: The route 0 to 1 to 3 costs 700 with one stop. Going 0 to 1 to 2 to 3 costs only 400 but needs two stops.
Example 2
0 and must reach city 2, and k = 0 permits at most 0 intermediate cities, so a route is legal only when it uses at most 1 flight.Input: flights = [[0,1,100],[1,2,100],[0,2,500]], n = 3, k = 0 Output: 500 Explanation: With no stops allowed, only the direct flight is usable.
Example 3
2 at all here, so the answer is -1 and the stop limit never comes into it.Input: flights = [[0,1,100]], n = 3, k = 5 Output: -1 Explanation: City 2 has no incoming flight at all, so it cannot be reached however many stops are allowed.
Constraints
- 1 <= n <= 100
- 0 <= flights.length <= n * (n - 1)
- 1 <= price <= 10^4
- 0 <= k < n
Editorial — intuition, approach, complexity and pitfalls
Intuition
Plain shortest-path reasoning gives the wrong answer here, and example 1 shows exactly why: the cheapest route costs 400 and uses two stops, which the limit forbids. The stop count is not a tiebreak, it is a second dimension of the problem.
That suggests tracking cost per number of flights taken rather than cost per city. A route using at most k stops is a route of at most k + 1 flights, so the answer is the cheapest way to reach the destination in that many hops or fewer.
Written that way the structure is simple: start with "city 0 reachable for 0, everything else unreachable", then relax every flight once to get the best costs using one flight, again for two, and so on — k + 1 rounds in total. Each round has to read the previous round’s costs, not the ones it is writing, or a single round could chain several flights together and quietly exceed the limit.
Approach
- Keep an array of the cheapest known cost to each city, starting at 0 for city 0 and infinity elsewhere.
- Repeat
k + 1times: take a copy of the current costs, and for every flight[from, to, price]whosefromis reachable in the copy, lower the cost oftotocopy[from] + priceif that is cheaper. - Writing into the live array while reading from the copy is what caps each round at one extra flight.
- After the rounds, return the destination’s cost, or
-1if it is still infinite.
Walkthrough
flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]]
n = 4, k = 1 so at most 2 flights, destination 3
round cost[0] cost[1] cost[2] cost[3]
start 0 inf inf inf
after 1 flight 0 100 inf inf
after 2 flights 0 100 200 700
answer 700
A third round would find 0 -> 1 -> 2 -> 3 for 400, which is
cheaper and uses two stops -- one more than allowed. The
round count IS the constraint.Complexity
- Time — O(k * m): k + 1 rounds over m flights. Searching by cheapest-first instead needs the stop count in the state, or it settles a city at a cost that uses too many stops.
- Space — O(n): two cost arrays.
Common Pitfalls
- Relaxing in place without the copy. One round then chains arbitrarily many flights and the stop limit stops meaning anything.
- Confusing stops with flights.
kstops isk + 1flights, so the loop runsk + 1times — example 2 hask = 0and still allows the direct flight. - Reaching for a plain cheapest-first search. It settles each city once, at a cost that may use more stops than allowed, and then cannot revisit it with a dearer-but-shorter route.
- Treating the flights as two-way. They are one-way, and example 1 contains a flight back to city 0 that is useless.
Full Solution — all languages
class Solution:
def findCheapestPrice(self, times, n, k):
INF = float("inf")
cost = [INF] * n
cost[0] = 0
for _ in range(k + 1):
previous = cost[:]
for frm, to, price in times:
if frm < n and to < n and previous[frm] + price < cost[to]:
cost[to] = previous[frm] + price
return -1 if cost[n - 1] == INF else cost[n - 1]import java.util.*;
class Solution {
public int findCheapestPrice(int[][] times, int n, int k) {
final long INF = Long.MAX_VALUE / 4;
long[] cost = new long[n];
Arrays.fill(cost, INF);
cost[0] = 0;
for (int round = 0; round <= k; round++) {
long[] previous = cost.clone();
for (int[] f : times) {
if (f[0] < n && f[1] < n && previous[f[0]] + f[2] < cost[f[1]]) {
cost[f[1]] = previous[f[0]] + f[2];
}
}
}
return cost[n - 1] >= INF ? -1 : (int) cost[n - 1];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int findCheapestPrice(vector<vector<int>>& times, int n, int k) {
const long long INF = LLONG_MAX / 4;
vector<long long> cost(n, INF);
cost[0] = 0;
for (int round = 0; round <= k; round++) {
vector<long long> previous = cost;
for (auto& f : times) {
if (f[0] < n && f[1] < n && previous[f[0]] + f[2] < cost[f[1]]) {
cost[f[1]] = previous[f[0]] + f[2];
}
}
}
return cost[n - 1] >= INF ? -1 : (int)cost[n - 1];
}
};/**
* @param {number[][]} times
* @param {number} n
* @param {number} k
* @return {number}
*/ var findCheapestPrice = function(times, n, k) {
const INF = Infinity;
const cost = new Array(n).fill(INF);
cost[0] = 0;
for (let round = 0; round <= k; round++) {
const previous = cost.slice();
for (const f of times) {
if (f[0] < n && f[1] < n && previous[f[0]] + f[2] < cost[f[1]]) {
cost[f[1]] = previous[f[0]] + f[2];
}
}
}
return cost[n - 1] === INF ? -1 : cost[n - 1];
};