Cheapest Flights Within K Stops

Medium

Topics
Dynamic ProgrammingGraphHeapShortest Path

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

1001001006002000123
start citydestination
Each arrow is one flight and the number on it is its price. You start at city 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.
Flights are one-way, so an arrow cannot be taken backwards.
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

100100500012
start citydestination
You start at city 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

100012
start citydestination
No sequence of flights reaches city 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

  1. Keep an array of the cheapest known cost to each city, starting at 0 for city 0 and infinity elsewhere.
  2. Repeat k + 1 times: take a copy of the current costs, and for every flight [from, to, price] whose from is reachable in the copy, lower the cost of to to copy[from] + price if that is cheaper.
  3. Writing into the live array while reading from the copy is what caps each round at one extra flight.
  4. After the rounds, return the destination’s cost, or -1 if 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. k stops is k + 1 flights, so the loop runs k + 1 times — example 2 has k = 0 and 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]
SensAI
Beta
Tap the mic to stop voice mode