SDE & MLE Prep

787. Cheapest Flights Within K Stops

Problem

flights[i] = [from, to, price] are one-way flights between cities 0…n − 1. Return the cheapest price from src to dst using at most k stops (so at most k + 1 flights), or −1 if there is no such route.

Example: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 → 700 (0 → 1 → 3)

At most k stops = at most k+1 edges → run k+1 rounds of Bellman–Ford relaxation, each round relaxing from a copy of the previous distances (so one round adds at most one edge).

round 0: dist {0:0}
round 1: dist {0:0, 1:100}
round 2: dist {0:0, 1:100, 2:200, 3:700}    k=1 -> answer dist[3] = 700

Complexity: O(k · E).

class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
        INF = float("inf")
        dist = [INF] * n
        dist[src] = 0
        for _ in range(k + 1):
            nxt = dist[:]
            for u, v, w in flights:
                if dist[u] + w < nxt[v]:
                    nxt[v] = dist[u] + w
            dist = nxt
        return -1 if dist[dst] == INF else dist[dst]