Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Cheapest fare with at most k stops

Medium · Target 25 minutes · Graphs · Type asked atAmazonGoogleAirbnb

There are n cities numbered 0 to n − 1. Each triple [from, to, price] in flights is a one-way flight. Return the cheapest total price from src to dst using at most k stops (so at most k + 1 flights), or −1 if no such route exists.

Examples

InputOutputWhy
n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 17000 → 1 → 3 costs 700. 0 → 1 → 2 → 3 costs 400 but needs two stops.
n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1200One stop is allowed.
same flights, k = 0500Only the direct flight.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ flights.length ≤ n(n − 1)/2
  • 1 ≤ price ≤ 10⁴
  • 0 ≤ k < n
  • src ≠ dst

Hints

Hint 1

Dijkstra keeps only the cheapest way to reach each city, but the cheapest way may use too many stops while a dearer one would leave room to continue.

Hint 2

After round i of Bellman–Ford, the distances are exact for routes of at most i flights. Run exactly k + 1 rounds.

Hint 3

Within a round, read only the distances from the previous round. Otherwise one round can chain two flights.

Where people lose marks

  • Running k rounds instead of k + 1: k stops means k + 1 flights.
  • Updating costs in place within a round, which lets one round use several flights.
  • Running Dijkstra on cities alone and stopping when dst is popped.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.