Skip to problem
←

Cheapest Flights Within K Stops

Medium 0 attempts

There's a flight network of n cities connected by one-way flights, where each entry in flights is [from, to, price]. Starting at city src, find the lowest total price to reach city dst while making at most k stops along the way, and return that price. A stop is an intermediate city, so at most k + 1 flight edges are allowed. Return -1 when no qualifying route exists.

Function contract

Implement findCheapestPrice(n, flights, src, dst, k). Each flight is [from, to, price]; cities are numbered 0 through n - 1.

Output: The cheapest price using at most k intermediate stops (k + 1 flights), or -1 if unreachable. If src equals dst, return 0.

Example 1

Input
n = 4
flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]]
src = 0
dst = 3
k = 1
Output
700

Example 2

Input
n = 3
flights = [[0,1,10],[1,2,10],[0,2,100]]
src = 0
dst = 2
k = 0
Output
100

Example 3

Input
n = 3
flights = [[0,1,10]]
src = 0
dst = 2
k = 1
Output
-1
Visual Aid
Stops count intermediate cities
0 ─────────────→ 2 cost 1000 ─────→ 1 ────→ 2 cost 20k = 0: only the direct routek = 1: choose the cheaper route

This is example 2 with k compared at 0 and 1. Two flights require one intermediate stop.

Constraints
  • 1 <= n <= 100
  • 0 <= flights.length <= n*(n-1)/2
  • 0 <= src, dst, k < n
  • 1 <= price <= 10^4
  • Every flight endpoint is a valid city; no flight goes from a city to itself.
  • Each ordered pair of cities has at most one listed flight.

Bellman-Ford (K+1 iterations)

Relax edges k + 1 times. Read only from the previous pass and write into a copied array so each pass adds at most one flight; in-place updates could accidentally use too many stops.

javascript
function findCheapestPrice(n, flights, src, dst, k) {
  let prices = Array(n).fill(Infinity);
  prices[src] = 0;
  for (let i = 0; i <= k; i++) {
    const temp = [...prices];
    for (const [u, v, w] of flights) {
      if (prices[u] !== Infinity) temp[v] = Math.min(temp[v], prices[u] + w);
    }
    prices = temp;
  }
  return prices[dst] === Infinity ? -1 : prices[dst];
}

Time: O((k + 1) × (n + E)), including the price-array copy each pass. Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript