Skip to content
Preptima
mediumCodingConceptMidSeniorStaff

Find the cheapest flight from one city to another using at most K stops. Why does plain Dijkstra give the wrong answer?

Plain Dijkstra minimises cost alone, so it can return a cheap route with too many stops, and settling each city once discards a dearer route that still has stops to spare. Make the state city plus edges used, or run Bellman-Ford for exactly K + 1 rounds, each reading only the previous round's distances.

5 min readUpdated 2026-10-10Target archetype: Big Tech

Answer

Short answer

Plain Dijkstra minimises cost and ignores the stop limit, so it happily returns a cheap route with too many stops. Adding a stop counter is not enough if you still settle each city once. The cheapest way to reach a city may have used up the budget, and Dijkstra then throws away a dearer route that had stops to spare. The fix is to make the state (city, edges used), or to run Bellman-Ford for exactly K + 1 rounds.

Was this answer helpful?

Likely follow-ups

  • Return the actual itinerary, not just the price. What do you have to store per round?
  • Fares can be negative. Which of your two solutions still works, and why?
  • K is close to the number of cities. Which version would you ship, and what does it cost?
  • Now minimise the number of stops first and the price second. What changes in the heap ordering?

Related questions