Cheapest Flights Within K Stops solution explained
Cheapest Flights Within K Stops asks for the lowest total fare from one city to another using at most k stops in between, which means at most k + 1 flights, or -1 if no such route exists. Run Bellman-Ford for exactly k + 1 rounds, reading only the previous round's fares, so round r holds the cheapest fare using r flights or fewer. That takes O(k × E) time and O(V) space.
By Evin JohnPublished 9 min read
The problem, in plain terms
A travel site lists n cities, numbered 0 to n - 1, and a set of one-way flights, each with a fare. A traveler wants to get from a source city to a destination city but will accept at most k stops along the way, where a stop is any city other than the source and destination that the route passes through. Return the lowest possible total fare under that limit. If no route fits, return -1.
flights (from, to, fare): (0,1,10) (1,2,10) (2,3,10) (0,2,35) (0,3,70)
source = 0, destination = 3
k = 2: 0 -> 1 -> 2 -> 3 fare 30 (2 stops)
k = 1: 0 -> 2 -> 3 fare 45 (1 stop)
k = 0: 0 -> 3 fare 70 (no stops)The same map gives three different answers as the limit tightens, and that is the heart of the problem. With k = 1 the cheapest route overall, which goes through cities 1 and 2, is not allowed, so the answer becomes 45. Notice too that city 2 is reached most cheaply through city 1 (fare 20), but that route uses up the stop budget, so the pricier direct flight to city 2 (fare 35) is the one that matters.
Clarify before coding: are fares always positive? Can there be two flights between the same pair at different fares? If the source equals the destination, is the answer 0? And confirm the stop definition: k stops allows k + 1 flights.
What interviewers are looking for
Most candidates recognize a shortest-path problem and reach for Dijkstra. The interviewer is waiting to see whether you notice that a limit on the number of edges changes the rules. Explaining why the textbook algorithm breaks, with a concrete example, is worth as much as the final code. Good candidates then pick an algorithm whose structure already counts edges, which is exactly what Bellman-Ford's rounds do.
Brute force: try every short route
A depth-first search from the source that follows every flight, stops after k + 1 flights, and records the cheapest fare whenever it lands on the destination is correct. With an average of d outgoing flights per city it explores up to about d raised to the power k + 1 routes, which explodes quickly. It is still useful as a test oracle on tiny maps.
Why plain Dijkstra and in-place updates go wrong
Standard Dijkstra finalizes each city the first time it is taken from the heap, at its cheapest fare. In the example with k = 1, city 2 is finalized at fare 20 through city 1. That route has already used both allowed flights, so it cannot continue to city 3. The fare-35 direct route to city 2, which could continue, is thrown away because city 2 is already final. The algorithm ends up returning 70 instead of 45.
A similar trap waits in Bellman-Ford. If you update fares in place during a round, a fare written early in the round can be extended later in the same round, so one round can chain several flights. With the flights listed in the order above and k = 0, an in-place round sets city 1 to 10, then city 2 to 20, then city 3 to 30, and reports 30 even though only the direct flight at 70 is allowed. Each round must read the previous round's fares.
Optimal approach: Bellman-Ford limited to k + 1 rounds
Keep an array of the cheapest known fare to each city, starting at 0 for the source and infinity elsewhere. Run exactly k + 1 rounds. In each round, copy the array, then for every flight try to improve the copy using the fare from the original. After round r, each entry is the cheapest fare using at most r flights. After k + 1 rounds, read the destination.
def cheapest_within(n, flights, src, dst, k):
INF = float("inf")
fare = [INF] * n
fare[src] = 0
for _ in range(k + 1): # at most k + 1 flights
nxt = fare[:] # read last round, write this one
for a, b, price in flights:
if fare[a] + price < nxt[b]:
nxt[b] = fare[a] + price
fare = nxt
return -1 if fare[dst] == INF else fare[dst]Starting each round from a copy, rather than from infinity, keeps routes that use fewer flights. That matters: the cheapest valid answer might use only one flight even when k is large. You can also stop early if a round changes nothing, which is a small, safe optimization.
Alternative: Dijkstra over (city, flights used)
Dijkstra can be rescued by making the number of flights part of the state. The heap holds (fare, city, flights used). The first time the destination is popped, its fare is the answer. To avoid exploring hopeless states, remember for each city the fewest flights used by any state popped there so far. A later state at that city has a fare at least as high, so it is only worth expanding if it used strictly fewer flights.
#include <array>
#include <climits>
#include <functional>
#include <queue>
#include <tuple>
#include <utility>
#include <vector>
int cheapestWithin(int n, const std::vector<std::array<int, 3>>& flights,
int src, int dst, int k) {
std::vector<std::vector<std::pair<int, int>>> out(n);
for (const auto& f : flights) out[f[0]].push_back({f[1], f[2]});
using State = std::tuple<long long, int, int>; // fare, city, flights used
std::priority_queue<State, std::vector<State>, std::greater<State>> pq;
std::vector<int> fewest(n, INT_MAX); // fewest flights among popped states
pq.push({0, src, 0});
while (!pq.empty()) {
auto [fare, city, used] = pq.top();
pq.pop();
if (city == dst) return static_cast<int>(fare);
if (used >= fewest[city]) continue; // dominated: costlier and no fewer flights
fewest[city] = used;
if (used == k + 1) continue; // flight budget spent
for (const auto& [to, price] : out[city])
pq.push({fare + price, to, used + 1});
}
return -1;
}Each city can be expanded at most k + 2 times, once per strictly smaller flight count, so the heap handles O(k × E) entries in the worst case. On many inputs it stops much sooner, because it returns as soon as the destination surfaces. Bellman-Ford is easier to get right under pressure; this version is a good follow-up if the interviewer asks for something faster in practice.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Depth-first search over every route | Up to O(d^(k+1)) for average out-degree d | O(k) for the recursion |
| Plain Dijkstra | Fast, but wrong under a flight limit | n/a |
| Bellman-Ford, k + 1 rounds with a copy | O(k × E), plus O(k × V) for the copies | O(V) |
| Dijkstra on (city, flights used) | O(k × E × log(k × E)) worst case | O(k × E) for the heap |
Edge cases to try
- k = 0: only a direct flight counts.
- The source equals the destination: a fare of 0 with no flights.
- Two flights between the same pair at different fares: the cheaper one should win.
- The destination is unreachable: -1.
- A cheap route with too many stops next to an expensive short one, as in the example.
- A large k on a small map: the answer equals the ordinary cheapest route.
Mistakes to avoid
- Running k rounds instead of k + 1, so the limit is off by one.
- Updating fares in place within a round, which lets a single round use several flights.
- Finalizing each city once, as plain Dijkstra does.
- Initializing each round's array to infinity instead of to the previous round, which forces routes to use exactly r flights.
- Returning infinity or a sentinel instead of -1 when the destination is never reached.
Follow-ups
- Return the route, not just the fare. Store a parent per city per round in Bellman-Ford, or a parent per state in the Dijkstra version, and walk back.
- Fares can be negative. Bellman-Ford with a fixed number of rounds still works, because the round limit stops it from looping forever. The Dijkstra version does not.
- Limit total travel time as well as stops. Now there are two budgets, and the state grows to include both; this usually leads to a dynamic programming table or a pruned search.
- Many queries on the same map. Precompute a table of cheapest fares by number of flights for each source, if memory allows.
How to explain it out loud
Fictional example
- Candidate
- This looks like Dijkstra, but the stop limit changes things. The cheapest way into a middle city might use up the budget, while a pricier way with fewer flights could still continue.
- Candidate
- So I want an algorithm that counts flights. Bellman-Ford does that naturally: after r rounds, each fare uses at most r flights. k stops means k + 1 flights, so k + 1 rounds.
- Candidate
- Each round reads a copy of the last round, otherwise one round could chain several flights. That is O(k times E) time and linear space.
- Interviewer
- Could Dijkstra still work?
- Candidate
- Yes, if the state is the city plus flights used, and I only skip a state when an earlier, cheaper one at that city used no more flights.
Related problems
Network Delay Time is the unconstrained version, where Dijkstra applies directly. Word Ladder is shortest path with every step costing the same. To revisit directed graphs from a different angle, try Course Schedule and Course Schedule II. Every walkthrough is listed on the coding problems hub.
Natively during your prep
This problem is a good rehearsal for explaining why a familiar algorithm does not apply. In a practice session on Mac or Windows, Natively can read the route problem from a screenshot and suggest the bounded Bellman-Ford approach, along with the off-by-one between stops and flights. The transcript of your mock interview lets you check afterward whether you produced a counterexample for plain Dijkstra or just asserted it. Learn more on the AI interview assistant page.
Questions people ask
How do you solve Cheapest Flights Within K Stops?
Run Bellman-Ford for k + 1 rounds, since k stops allow k + 1 flights. Each round copies the previous fares and relaxes every flight using only the old values. Read the destination's fare at the end, or return -1 if it is still infinite.
Why doesn't plain Dijkstra work here?
Dijkstra finalizes each city at its cheapest fare, but that cheapest route may already use too many flights to continue. A pricier route with fewer flights gets thrown away even though it is the only one that fits the limit.
Why does Bellman-Ford need a copy of the array each round?
Updating in place lets a fare written earlier in a round be extended later in the same round, so one round can chain several flights and break the stop limit. Reading the previous round keeps one flight per round.
What is the time complexity?
Bounded Bellman-Ford is O(k × E) time and O(V) space. A Dijkstra over (city, flights used) states handles up to O(k × E) heap entries, so O(k × E × log(k × E)) in the worst case.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
