Graphs
Cheapest Flights Within K Stops
DESCRIPTION (inspired by Leetcode.com)
A travel booking system needs to find the lowest-cost route between airports. You're given n cities connected by flights, where each flight [from, to, price] represents a direct route with its cost.
Find the cheapest route from src to dst that uses at most k layovers (intermediate cities). If no such route exists, return -1.
Note: A route with k layovers means visiting k intermediate cities, or equivalently, taking k+1 flights.
Example 1:
Input:
n = 4 flights = [[0,1,100], [1,2,100], [2,3,100], [0,3,500]] src = 0 dst = 3 k = 1
Output:
500
Explanation: The route 0→1→2→3 costs $300 with 2 layovers (cities 1 and 2), which exceeds k=1. The direct flight 0→3 costs $500 with 0 layovers. Even though it's more expensive, it's the only valid route.
Example 2:
Input:
n = 4 flights = [[0,1,100], [1,2,100], [2,3,100]] src = 0 dst = 3 k = 1
Output:
-1
Explanation: The only path 0→1→2→3 requires 2 layovers (cities 1 and 2), but we're limited to k=1. No valid route exists.
Explanation
Understanding the Problem
First Intuition: Can We Use Dijkstra?
Testing Standard Dijkstra
Why Standard Dijkstra Fails
The Solution: Track Both City and Stops
How the Algorithm Works
Walkthrough
Solution
When to Use This Pattern
Alternative: Bellman-Ford Approach
Connection to Network Delay Time
Purchase Premium to Keep Reading
Unlock this article and so much more with Hello Interview Premium
Unlock Premium Coding Content
On This Page