Skip to the solution
MediumDSA15 min read

How do you find the cheapest flight with at most K stops?

133 views

The problem

Question presented to candidate: "There are n cities and a list of one-way flights, each given as [from, to, price]. Given a source, a destination and a number K, find the cheapest price from source to destination with at most K stops, or return -1 if there is no such route. Please code it in Python."

What a strong answer should cover:

  • Model it as a directed weighted graph and translate "at most K stops" into "at most K + 1 flights".
  • Explain why plain Dijkstra is wrong here: a cheaper arrival with more flights can be a dead end, so the state must include the flight count.
  • Bounded Bellman-Ford: K + 1 rounds of relaxing every flight, reading last round's prices and writing a copy (cost[:]), in O((K + 1) ยท E) time and O(n) space.
  • The alternative Dijkstra over (cost, flights, city) states with heapq, and why it can skip a pop only when an earlier pop used no more flights.
  • Python details: float("inf") as "unreachable" (and converting it back to -1), cost[:] or list(cost) for a shallow copy, and heapq being a min-heap over tuples.
  • Edge cases: source equals destination, unreachable destination, K = 0.

Clarifying questions expected:

  • Does K stops mean K intermediate cities, so K + 1 flights?
  • Are prices always positive, and what should be returned when there is no route?

Code / implementation expected: Yes โ€” find_cheapest_price(n, flights, src, dst, k) in Python 3, with bounded Bellman-Ford (or a heap-based state search).

  • dsa
  • graph
  • shortest-path
  • bellman-ford

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

15 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonBellman-Ford limited to k + 1 rounds (7 inputs)
PythonTwo classic bugs, and a 1,000-graph cross-check against brute force

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 123 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

What is the Union-Find (Disjoint Set) data structure?

Continue