← DSA
MEDIUM

Cheapest Flights Within K Stops

PracticeNeetCode ↗LeetCode ↗

Given n cities connected by flights with prices, find the cheapest price from src to dst using at most k stops along the way. Return -1 if no such route exists.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Initialize a distances array of size n with infinity, except distances[src] = 0.
  2. Repeat k + 1 times: copy the current distances into a temporary array.
  3. For each flight (u, v, price), if distances[u] + price is cheaper than the temporary array's current value at v, update the temporary array.
  4. Replace distances with the temporary array after each full round.
  5. Return distances[dst] if it's still finite after all rounds, otherwise -1.

Complexity

Time: O(k · E) — Space: O(n)

Code

def findCheapestPrice(n: int, flights: list[list[int]], src: int, dst: int, k: int) -> int:
    distances = [float("inf")] * n
    distances[src] = 0

    for _ in range(k + 1):
        updated = distances.copy()
        for u, v, price in flights:
            if distances[u] != float("inf") and distances[u] + price < updated[v]:
                updated[v] = distances[u] + price
        distances = updated

    return distances[dst] if distances[dst] != float("inf") else -1

Code Explanation

How the solution above works, piece by piece.

  1. distances[v] = cheapest known price from src to v; only src starts at 0.
  2. Run k + 1 rounds, because k stops means at most k + 1 flights.
  3. Each round relaxes every flight u → v, but reads from the previous round's array and writes into updated. Without the copy, one round could use several flights in a row and break the stop limit.
  4. After the rounds, distances[dst] is the best price with at most k stops, or −1 if unreachable.
  5. O(k · E) time, O(n) space.

Visual Walkthrough

Running it on the example with src = 0, dst = 3, k = 1:

Flight graph and Bellman-Ford distances per round1001001006002000123distances after each roundstart0∞∞∞round 10100∞∞round 20100200700k = 1 stop → k + 1 = 2 rounds
Round i finds the cheapest price using at most i flights. With k = 1 stop, only 2 flights are allowed, so the cheaper 3-flight route 0→1→2→3 (400) is never considered; the answer is 0→1→3 = 700. Copying the array each round stops one round from chaining several flights.
cheapest route within 1 stop

Video Explanation

NeetCode — Bellman-Ford, Cheapest Flights Within K Stops, LeetCode 787