Imagine you're a travel agent trying to find the most budget-friendly flight route for your client. You have access to a network of n cities connected by various flights, where each flight has a specific cost.

You're given an array flights where flights[i] = [from_i, to_i, price_i] represents a direct flight from city from_i to city to_i costing price_i dollars. Your client wants to travel from a source city src to a destination city dst, but here's the catch: they can make at most k stops along the way.

Your mission: Find the cheapest possible price for this journey. If no valid route exists within the stop limit, return -1.

Example: If there are flights [0,1,100], [1,2,100], [0,2,500] and you want to go from city 0 to city 2 with at most 1 stop, you should choose the route 0→1→2 (cost: 200) instead of the direct flight 0→2 (cost: 500).

Input & Output

example_1.py — Basic Flight Network
$ 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
💡 Note: With at most 1 stop, the optimal path is 0→1→3 with cost 100+600=700. The path 0→2→3 costs 100+200=300 but requires going through city 2, which would need the expensive flight from 0→2.
example_2.py — Multiple Path Options
$ Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
💡 Note: We can go directly 0→2 for $500, or via 1 stop: 0→1→2 for $100+$100=$200. Since k=1 allows 1 stop, we choose the cheaper route with cost 200.
example_3.py — No Valid Route
$ Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
💡 Note: With k=0 (no stops allowed), we can only take direct flights. The only direct flight from 0→2 costs $500, so that's our answer.

Time & Space Complexity

Time Complexity
⏱️
O(k * E)

We iterate k+1 times, and for each iteration process all E flights

n
2n
Linear Growth
Space Complexity
O(k * n)

DP table stores costs for each (stops, city) combination

n
2n
Linearithmic Space

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ flights.length ≤ n * (n - 1) / 2
  • flights[i].length == 3
  • 0 ≤ fromi, toi < n
  • fromi ≠ toi
  • 1 ≤ pricei ≤ 104
  • There will not be any multiple flights between two cities
  • 0 ≤ src, dst, k < n
  • src ≠ dst
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen