</>

787. Cheapest Flights Within K Stops

Medium NeetCode 150
Advanced Graphs Time O(k * E) Space O(n)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Advanced Graphs
Time
O(k * E)
Space
O(n)

Standard Solution (C++)

SummaryFind the cheapest fare from a source city to a destination city using at most k intermediate stops, or report that no such route exists.

Approach

Bellman-Ford limited to k+1 relaxation rounds.

  • Maintain best-known costs to every city.
  • Perform k+1 passes; in each pass relax all edges, but read from a snapshot of the previous pass so each round adds at most one more flight.
  • After the passes, the destination's cost is the answer (or -1 if still infinite).
class Solution {
public:
    int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
        const int INF = 1e9;
        vector<int> cost(n, INF);
        cost[src] = 0;
        for (int i = 0; i <= k; ++i) {
            vector<int> tmp = cost;
            for (auto& f : flights) {
                int u = f[0], v = f[1], w = f[2];
                if (cost[u] == INF) continue;
                tmp[v] = min(tmp[v], cost[u] + w);
            }
            cost = tmp;
        }
        return cost[dst] == INF ? -1 : cost[dst];
    }
};
Time O(k * E) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern