Cheapest Flights Within K Stops (LeetCode 787): Solution and Explanation

Medium
Dynamic Programming
Depth First Search
Breadth First Search
Graph
Heap
Shortest Path

You are given a set of one-way flights between n cities, each with a price, plus a source, a destination and a limit k on intermediate stops. Return the lowest total price of any route from the source to the destination that uses at most k stops, or -1 if no such route exists.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Without the stop limit this would be a plain cheapest path problem, and Dijkstra would be the obvious tool. The limit changes things. A route that is cheap but uses many hops may be illegal, while a pricier route with fewer hops is the real answer, so the usual rule of settling each city once at its best price breaks down. The brute force is to enumerate every path of at most k + 1 edges, which explodes exponentially in dense graphs.

The key reframing is that k stops means at most k + 1 flights. Bellman-Ford already works in rounds where round i finds the cheapest price to every city using at most i edges. Normally you run n - 1 rounds to cover every possible path length. Here you simply stop after k + 1 rounds, and whatever price sits at the destination is the cheapest route that respects the limit.

There is one subtlety. Inside a round, if you update prices in place, an improvement made earlier in the same round can feed into a later edge, letting a single round extend a path by two or more flights. That silently breaks the hop count. Copying the price array at the start of each round and reading only from the old copy while writing to the new one guarantees each round adds exactly one more flight.

Approach: Bellman-Ford limited to k + 1 rounds

  1. Create prices with infinity for every city and set prices[src] = 0.
  2. Repeat k + 1 times, once for each flight a route is allowed to use.
  3. At the start of each round copy prices into tmpPrices so updates in this round cannot chain together.
  4. For every flight (s, d, p), skip it if prices[s] is still infinity, since the source city has not been reached yet.
  5. Otherwise, if prices[s] + p beats tmpPrices[d], write the smaller value into tmpPrices[d].
  6. After scanning all flights, replace prices with tmpPrices.
  7. When the rounds finish, return prices[dst], or -1 if it is still infinity.

Step-by-step example

n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
  1. Start with prices = [0, inf, inf]. Since k = 1, we run two rounds.
  2. Round 1: copy to tmpPrices = [0, inf, inf]. Flight 0 to 1 gives 0 + 100 = 100, so tmpPrices[1] = 100.
  3. Still round 1: flight 1 to 2 is skipped because prices[1] is infinity in the old array. Flight 0 to 2 gives 500, so tmpPrices[2] = 500. Now prices = [0, 100, 500].
  4. Round 2: copy to tmpPrices = [0, 100, 500]. Flight 0 to 1 gives 100, no improvement. Flight 1 to 2 gives 100 + 100 = 200, which beats 500, so tmpPrices[2] = 200.
  5. Flight 0 to 2 gives 500, no improvement. After the round prices = [0, 100, 200].
  6. Return prices[2] = 200, the route 0 to 1 to 2 with one stop. With k = 0 the loop would stop after round 1 and return 500.

Code: Python, Java, C++

1class Solution:
2    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
3        prices = [float("inf")] * n
4        prices[src] = 0
5        
6        for i in range(k + 1):
7            tmpPrices = prices.copy()
8            
9            for s, d, p in flights:
10                if prices[s] == float("inf"):
11                    continue
12                if prices[s] + p < tmpPrices[d]:
13                    tmpPrices[d] = prices[s] + p
14            prices = tmpPrices
15        return -1 if prices[dst] == float("inf") else prices[dst]

Time and space complexity

Time

O(k × E)

There are k + 1 rounds and each round scans every one of the E flights once, plus an O(n) copy of the price array, giving O(k × (n + E)), which is usually written as O(k × E).

Space

O(n)

Only the two price arrays of length n are stored. The flight list is read directly without building an adjacency list.

Other approaches

BFS by levels with pruning (time O(k × E), space O(n + E))

Run a BFS where each level is one more flight, carrying (city, cost) pairs and keeping the best cost seen per city to prune. Stop after k + 1 levels. It explores the same layered structure as the limited Bellman-Ford but can skip unreachable regions early.

Dijkstra with a stops dimension (time O(E × k × log(E × k)), space O(n × k + E))

Push (cost, city, stops) into a min-heap and only expand states whose stop count is within the limit, tracking the fewest stops seen at each city to avoid re-expanding dominated states. It is often faster in practice on sparse graphs but is trickier to get right.

Common mistakes

  • Updating prices in place during a round, which lets one round chain several flights together and quietly exceeds the k stop limit.
  • Running k rounds instead of k + 1. The limit counts intermediate stops, so the number of flights allowed is one more than k.
  • Using plain Dijkstra that marks a city as done at its cheapest price, which throws away a more expensive path that has fewer stops and is the only legal one.
  • Adding a price to infinity in a language with fixed-width integers. Skip the edge when the source price is unreached instead of relying on overflow.

Frequently asked questions

Why does the solution copy the prices array each round?

The copy makes each round extend paths by exactly one flight. If you updated in place, a price lowered earlier in the round could be used again later in the same round, producing a path with more flights than the round number allows and breaking the stop limit.

Why doesn't regular Dijkstra work for cheapest flights within k stops?

Dijkstra finalizes each city the first time it is popped at its cheapest cost. With a stop limit, the cheapest way to reach a middle city may use too many stops, while a slightly pricier way with fewer stops is the one that leads to a valid answer. You need to track stops as part of the state, which plain Dijkstra does not do.

What is the time complexity of the Bellman-Ford solution?

It runs k + 1 rounds and each round touches every flight once, so the time is O(k × E). Space is O(n) for the two price arrays.

Can this be solved with BFS?

Yes. A level-by-level BFS where each level represents one flight works well, as long as you keep the best known cost per city to prune and stop after k + 1 levels. It has the same worst-case bound as the bounded Bellman-Ford.