InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Advanced Graphs

Cheapest Flights Within K Stops

medium Original ↗ 00:00

Problem

There are n cities numbered 0 to n - 1, connected by directed flights. Each flight is given as [u, v, price]: you can fly from city u to city v for price dollars.

Given a start city src, a destination dst, and an integer k, return the cheapest total price to travel from src to dst using at most k intermediate stops — i.e. a route of at most k + 1 flights. If no such route exists, return -1.

Note that the globally cheapest route may use too many stops, so plain shortest-path logic is not enough.

Examples

  • n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1700 — the cheaper route 0→1→2→3 (cost 400) needs 2 stops, so we must take 0→1→3.
  • Same graph with k = 2400 — now 0→1→2→3 is allowed.
  • n = 3, flights = [[0,1,100],[1,2,100]], src = 0, dst = 2, k = 0-1 — reaching city 2 requires stopping at city 1.

Constraints

  • 1 <= n <= 100
  • 0 <= len(flights) <= n * (n - 1), no duplicate edges
  • 1 <= price <= 10^4
  • 0 <= k < n, src != dst

Think about it first

Hint 1 "At most k stops" means "at most k + 1 edges". Rephrase the question as: what is the cheapest path from src to dst that uses at most k + 1 edges?
Hint 2 Why does ordinary Dijkstra fail here? Because the cheapest way to reach an intermediate city may use too many edges to continue to dst. You need to track cost per number of edges used, not just per city.
Hint 3 Bellman-Ford relaxes every edge once per round, and after r rounds it has found the cheapest paths using at most r edges. Run exactly k + 1 rounds — relaxing against a snapshot of the previous round so a single round can't chain two new edges — and read off the answer at dst.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug