MediumDynamic ProgrammingDepth-First SearchBreadth-First SearchGraphHeap (Priority Queue)Shortest Path

Cheapest Flights Within K Stops

LeetCode
1 approach, code in all languages

There are `n` cities connected by some flights. Each flight is given as `flights[i] = [from, to, price]`, meaning there is a one-directional flight from city `from` to city `to` costing `price`.

Given a starting city `src`, a target city `dst`, and an integer `k`, return the cheapest total price to travel from `src` to `dst` using at most `k` stops. A "stop" is an intermediate city, so a route with `k` stops uses up to `k + 1` flights.

If no route satisfies the stop limit, return `-1`.

Example 1

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

Output: 700

With at most 1 stop, the route 0 -> 1 -> 3 costs 700. The cheaper 0 -> 1 -> 2 -> 3 (400) uses 2 stops and is not allowed.

Example 2

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

Output: 500

No stops are allowed, so only the direct flight 0 -> 2 for 500 qualifies; 0 -> 1 -> 2 would require one stop.

Constraints

  • 1 <= n <= 100
  • 0 <= flights.length <= n * (n - 1) / 2
  • flights[i].length == 3
  • 0 <= from_i, to_i < n
  • from_i != to_i
  • 1 <= price_i <= 10^4
  • There is at most one flight between any ordered pair of cities.
  • 0 <= src, dst, k < n
  • src != dst
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now