27 · Shortest Paths

#787 Cheapest Flights Within K Stops

Mediumsolve on LeetCode ↗

frequently reported atAirbnbFlipkartAmazonGoogleMeta

the problem

In plain words

There are n cities and directed flights [from, to, price]. Find the cheapest price from src to dst using at most k stops (so at most k + 1 flights). Return -1 if impossible.

in n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1

out 700

0→1→3 costs 700. 0→1→2→3 costs 400 but uses 2 stops.

in n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1

out 200

in same, k = 0

out 500

No stops allowed → only the direct flight.

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

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #743
      Network Delay Time
      Mediumin Shortest Paths
    2. #1976
    3. #1091