Cheapest Flights Within K Stops

35 min · findCheapestPrice()

The rock-bottom fare isn't useful if it needs more layovers than your trip allows.

There are n airports numbered from 0 through n - 1. Each entry [u, v, w] in flights is a one-way flight from u to v costing w.

Return the lowest total price from src to dst while using at most k stops — airports visited between the starting airport and the destination. That means your route may use at most k + 1 flights. Return -1 if no route respects that limit. If src and dst are the same airport, the trip costs 0.

Every listed flight joins two different airports, and no directed airport pair appears twice.

Constraints

  • 1 <= n <= 100
  • 0 <= flights.length <= n * (n - 1)
  • Every flights[i] is [u, v, w] with 0 <= u, v < n, u != v, and 1 <= w <= 10_000.
  • Directed pairs (u, v) are distinct.
  • 0 <= src, dst < n
  • 0 <= k < n

Hints

Translate stops into edges

Zero stops allows one direct flight. In general, at most k stops means at most k + 1 edges in the route.

One round buys one flight

Start with price 0 at src and infinity elsewhere. During each round, use only prices from the previous round to relax every flight. Run exactly k + 1 rounds.

Why copy the prices?

Updating the same array in place could chain several flights during one round. A copied array keeps each round tied to one additional flight.

Follow-up

If the stop limit disappeared, which non-negative shortest-path algorithm would you choose instead?

Visible cases

Examples

Example 1

ready
Input
n = 4
flights = [
  [
    0,
    1,
    100
  ],
  [
    1,
    2,
    100
  ],
  [
    2,
    0,
    100
  ],
  [
    1,
    3,
    600
  ],
  [
    2,
    3,
    200
  ]
]
src = 0
dst = 3
k = 1
Expected
700
Why
0 → 1 → 3 costs 700 and uses one stop

Example 2

ready
Input
n = 4
flights = [
  [
    0,
    1,
    100
  ],
  [
    1,
    2,
    100
  ],
  [
    2,
    0,
    100
  ],
  [
    1,
    3,
    600
  ],
  [
    2,
    3,
    200
  ]
]
src = 0
dst = 3
k = 0
Expected
-1
Why
zero stops requires a direct flight, and none exists

Example 3

ready
Input
n = 3
flights = [
  [
    0,
    1,
    40
  ]
]
src = 1
dst = 1
k = 0
Expected
0
Why
staying at the starting airport costs nothing

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite