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.
k + 1 rounds of relaxation, since k stops means k + 1 flights.distances array of size n with infinity, except distances[src] = 0.k + 1 times: copy the current distances into a temporary array.(u, v, price), if distances[u] + price is cheaper than the temporary array's current value at v, update the temporary array.distances with the temporary array after each full round.distances[dst] if it's still finite after all rounds, otherwise -1.Time: O(k · E) — Space: O(n)
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 -1How the solution above works, piece by piece.
distances[v] = cheapest known price from src to v; only src starts at 0.k + 1 rounds, because k stops means at most k + 1 flights.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.distances[dst] is the best price with at most k stops, or −1 if unreachable.Running it on the example with src = 0, dst = 3, k = 1:
NeetCode — Bellman-Ford, Cheapest Flights Within K Stops, LeetCode 787