Cheapest Flights Within K Stops

Pattern: Shortest paths

medium

Find the cheapest price from src to dst using at most k stops (k + 1 flights). Relax flights layer by layer, one layer per flight taken, for k + 1 layers; this is Bellman-Ford limited by the number of edges.

The problem

Given n cities and directed flights [from, to, price], return the cheapest price from src to dst with at most k stops in between, or -1 if there is none.

Think first

  • How many flights do k stops allow?
  • Why does plain Dijkstra fail?
  • How do you count flights while relaxing?

Hints

    Brute force, and why it fails

    Try every route with at most k + 1 flights: exponential.

    The key insight

    Bellman-Ford's rounds are exactly 'routes with at most i edges', so k + 1 rounds answer the question.

    Dry run

    best0 100 - -

    Flights 0→1 100, 1→2 100, 2→0 100, 1→3 600, 2→3 200; src 0, dst 3, k = 1. After one flight: 1 = 100.

    Step 1 of 3

    The plan

    best[src] = 0; layer = [(src, 0)]
    repeat k + 1 times: for (city, cost) in layer: for flights: if cheaper: update and add to next layer
    

    Complexity

    Time
    O(k × E)
    Space
    O(V + E)

    Each round looks at each flight at most a few times.

    Edge cases

    • k = 0: only direct flights.
    • No route: -1.
    • src equals dst: 0.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
            List<List<int[]>> adj = new ArrayList<>();
            for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
            for (int[] f : flights) adj.get(f[0]).add(new int[]{f[1], f[2]});
            int[] best = new int[n];                // the cheapest cost found to each city with few enough stops
            Arrays.fill(best, Integer.MAX_VALUE);
            best[src] = 0;
            Queue<int[]> q = new ArrayDeque<>();    // {city, cost}, one layer per flight taken
            q.add(new int[]{src, 0});
            for (int flightsTaken = 0; flightsTaken <= k && !q.isEmpty(); flightsTaken++) {
                for (int size = q.size(); size > 0; size--) {
                    int[] cur = q.poll();
                    for (int[] e : adj.get(cur[0])) {
                        int cost = cur[1] + e[1];
                        if (cost < best[e[0]]) { best[e[0]] = cost; q.add(new int[]{e[0], cost}); }
                    }
                }
            }
            return best[dst] == Integer.MAX_VALUE ? -1 : best[dst];
        }
    }

    C++

    class Solution {
    public:
        int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
            vector<vector<pair<int, int>>> adj(n);
            for (const vector<int>& f : flights) adj[f[0]].push_back(make_pair(f[1], f[2]));
            vector<int> best(n, INT_MAX);           // the cheapest cost found to each city with few enough stops
            best[src] = 0;
            queue<pair<int, int>> q;                // {city, cost}, one layer per flight taken
            q.push(make_pair(src, 0));
            for (int flightsTaken = 0; flightsTaken <= k && !q.empty(); flightsTaken++) {
                for (int size = static_cast<int>(q.size()); size > 0; size--) {
                    pair<int, int> cur = q.front();
                    q.pop();
                    for (const pair<int, int>& e : adj[cur.first]) {
                        int cost = cur.second + e.second;
                        if (cost < best[e.first]) { best[e.first] = cost; q.push(make_pair(e.first, cost)); }
                    }
                }
            }
            return best[dst] == INT_MAX ? -1 : best[dst];
        }
    };

    Python

    class Solution:
        def findCheapestPrice(self, n: int, flights: list[list[int]], src: int, dst: int, k: int) -> int:
            adj = [[] for _ in range(n)]
            for u, v, w in flights:
                adj[u].append((v, w))
            best = [float("inf")] * n               # the cheapest cost found to each city with few enough stops
            best[src] = 0
            layer = [(src, 0)]                      # one layer per flight taken
            for _ in range(k + 1):
                nxt = []
                for city, cost in layer:
                    for v, w in adj[city]:
                        if cost + w < best[v]:
                            best[v] = cost + w
                            nxt.append((v, cost + w))
                layer = nxt
            return -1 if best[dst] == float("inf") else best[dst]

    Common mistakes

    • Updating distances inside a round so a route uses two flights in one round.
    • Allowing k + 2 flights.

    Similar problems