← Whiteboard questions

Cheapest Flights Within K Stops

Find the cheapest trip that stops at most k times

DSA, Medium, Advanced Graphs

Which structure or algorithm, and what does it cost.

An airline serves n airports numbered 0 to n - 1. Each triple [a, b, cost] in flights is a one-way flight from airport a to airport b that costs cost. A traveller must go from airport src to airport dst, and the traveller may stop at no more than k airports in between. Return the lowest total cost, or -1 if no trip fits. Two airports may have several flights between them.

Examples

Input n = 5, flights = [[0,1,40],[1,2,30],[2,4,20],[0,3,70],[3,4,60],[0,4,200]], src = 0, dst = 4, k = 1
Output 130
Why with one stop, the trip 0, 3, 4 costs 130. The trip 0, 1, 2, 4 costs only 90, but it makes two stops.
Input n = 4, flights = [[0,1,30],[1,3,30],[0,2,90],[2,3,10]], src = 0, dst = 3, k = 0
Output -1
Why no stop is allowed, and no flight goes straight from airport 0 to airport 3.
Input n = 2, flights = [[0,1,900],[0,1,400],[1,0,5]], src = 0, dst = 1, k = 3
Output 400
Why two flights join the same airports, and the cheaper one is used.

Constraints

Your answer must contain

Target Aim for O((k + 1) * r) time and O(n) memory, where r is the number of flights.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

What limits a trip besides its price? A cheaper trip may use more stops than you are allowed.

Hint 2 the approach

Think in rounds. In round one, find the cheapest price to reach each airport with a single flight. Then see how round two builds on round one.

Hint 3 the key step

Keep the best price to every airport. For k + 1 rounds, go through every flight and try to improve its end airport, reading last round's prices from a copy.

Walkthrough

Full walkthrough brute force to best

Brute force

Try every trip that uses at most k + 1 flights, add up its costs, and keep the cheapest one that ends at the destination. With r flights there can be r to the power k + 1 trips, so this only works for tiny cases.

Best method

A trip with at most k stops uses at most k + 1 flights, so run k + 1 rounds. Keep the cheapest known price to each airport, starting with 0 at the source and infinity elsewhere. In each round, copy the prices. For every flight, if the old price at its start airport plus the flight cost beats the copy's price at its end airport, update the copy. Then use the copy as the new prices. After round j, each price is the cheapest using at most j flights. Reading old prices and writing a copy matters: it stops one round from using two flights. This is the Bellman-Ford method with the number of rounds capped. After k + 1 rounds, return the price of the destination, or -1 if it is still infinite.

Hand trace

Example 1 has k = 1, so there are 2 rounds. The prices start as [0, inf, inf, inf, inf]. Round 1 uses one flight from the source and gives [0, 40, inf, 70, 200]. Round 2 reads those old prices. Airport 2 gets 40 + 30 = 70. Airport 4 gets 70 + 60 = 130 through airport 3, which beats 200. The flight from airport 2 to airport 4 adds nothing yet, because airport 2 was still infinite in the old prices. The prices are [0, 40, 70, 70, 130], so the answer is 130. The cheaper trip of price 90 needs a third round, which means two stops.

Code

def cheapest_route(n, flights, src, dst, k):
    price = [float("inf")] * n          # cheapest known price to each airport, using at most j flights
    price[src] = 0
    for _ in range(k + 1):              # k stops means at most k + 1 flights
        nxt = price[:]                  # read the old prices, write the copy
        for a, b, cost in flights:
            if price[a] + cost < nxt[b]:
                nxt[b] = price[a] + cost
        price = nxt
    return -1 if price[dst] == float("inf") else price[dst]

Time and memory

O((k + 1) * r) time: k + 1 rounds, each going through all r flights. O(n) memory for the two price lists.

Common mistakes

  • Running plain Dijkstra on price alone. The cheapest route to an airport may use too many stops and hide a dearer route with fewer stops.
  • Updating prices in place during a round. A price changed early in the round then lets one round use two flights. Read the old prices and write a copy.
  • Counting k flights instead of k + 1. With k stops in between there are k + 1 flights.
  • Returning infinity when the destination cannot be reached. Return -1.

Related problems

More Advanced Graphs problems
Cheapest Flights Within K Stops: walkthrough and solution