The Cheapest Flights Within K Stops problem requires finding the minimum cost path between two cities with a constraint on the number of stops allowed, making it a variant of shortest path algorithms with additional bounded constraints.
1. Problem Restatement
Clarifying questions to ask the interviewer:
- Can we assume that all flight prices are non-negative? What happens if there's no valid route?
- Are there any constraints on the number of cities or flights (e.g., max 100 cities, max 1000 flights)?
- Should we return the actual cheapest price or just the minimum cost value?
- Can we modify the input graph or do we need to work with a copy?
- What's the expected time complexity target? O(V * E) or better?
Restated problem: Given a directed weighted graph representing flights between cities, find the cheapest price to travel from a source city to a destination city with at most K stops (i.e., at most K+1 edges in the path). Each flight has a price (weight), and we want to minimize total cost while respecting the stop constraint.
Input/Output specification:
- Input:
n(number of cities, 1-indexed)flightsarray where each element is[from, to, price]src(source city)dst(destination city)k(maximum number of stops allowed)
- Output: Integer representing the minimum cost, or -1 if no valid path exists
Constraints:
- 1 ≤ n ≤ 100
- 0 ≤ flights.length ≤ (n * (n-1))/2
- 0 ≤ k ≤ n-1
- All flight prices are positive integers
Assumptions:
- Cities are numbered from 0 to n-1 (0-indexed)
- There may be multiple flights between the same pair of cities
- The graph may not be connected (some cities might be unreachable)
- We're looking for the cheapest path among all valid paths with ≤ K stops
Data shape and hidden structure: The problem involves a weighted directed graph where nodes represent cities and edges represent flights with prices. The constraint of "at most K stops" creates a bounded search space, making this a variant of shortest path problems with additional state constraints. The key insight is that we need to track both cost and number of stops to avoid suboptimal paths that are cheaper but exceed stop limits.
The problem has a hidden structure where we're essentially searching for the shortest path in a modified graph where each node is annotated with the number of stops used to reach it, and we only consider paths that respect the K-stop constraint.
2. Pattern Recognition
The problem exhibits characteristics of a shortest path graph algorithm with additional constraints on the number of stops. The key signals are:
- "Cheapest flights" - This immediately signals we're looking for minimum cost/path optimization, which is classic Dijkstra's or Bellman-Ford territory
- "Within K stops" - This adds a constraint on path length/depth, making it a variant of shortest path where we're bounded by the number of edges (stops) in our path
- "Flights" - This is clearly a graph problem where nodes are cities and edges are flights with weights (prices)
The core pattern here is bounded shortest path search. We're not just finding the shortest path, but the shortest path with at most K edges (stops) between two nodes. This is a constrained version of the single-source shortest path problem.
The key insight is that we need to track both:
- The minimum cost to reach each city
- The number of stops used to reach that city
This is fundamentally different from regular shortest path algorithms because we're not just minimizing cost, but also respecting a maximum edge count constraint.
This fits the Dynamic Programming + Graph Traversal pattern where we build up solutions incrementally while respecting the K-stop constraint.
The core insight is that we can use a modified Dijkstra's or BFS approach where we track the number of stops in our state, allowing us to prune paths that exceed K stops while still finding optimal cost paths within the constraint.
3. Approach Evolution
My first instinct is to use a modified Dijkstra's algorithm or BFS because this is fundamentally about finding the shortest path in a weighted graph, but with an additional constraint on the number of stops. However, that's O(n²) in the worst case because we might need to explore all possible paths up to K stops, and for each path we might have to re-evaluate nodes multiple times.
Let me think about how to optimize this. The key insight is that we can't simply use standard shortest path algorithms because they don't respect the K stops constraint. If I just run Dijkstra, I might find a path that's cheaper but has more than K stops, which violates the constraint.
I notice that if I maintain a state of (node, number_of_stops_used), I can reduce this to O((K+1) × n) where n is the number of nodes. This is because we can have at most K+1 different numbers of stops (0 through K), and for each stop count, we can have at most n nodes.
The core idea is to use a modified Dijkstra where instead of tracking just the minimum distance to each node, we track the minimum cost to reach each node with exactly i stops for i from 0 to K. This way, we can ensure that we never exceed K stops.
Let me think about the implementation:
- We want to find the cheapest path from source to destination with at most K stops
- Standard Dijkstra would work but doesn't respect the stop constraint
- We can use a priority queue that sorts by cost, but we also need to track the number of stops used
- We can use a modified BFS with level tracking where each level represents one more stop
The key optimization is to realize that we don't need to explore all paths - we can prune branches that exceed K stops or are more expensive than already found paths with the same number of stops.
I'll use a modified Dijkstra approach with state tracking:
- State: (node, cost, stops_used)
- Priority queue sorted by cost
- For each node, we only explore paths that respect the K constraint
- We can stop early if we've already found a better path to a node with the same or fewer stops
This approach will be O((K+1) × (V + E)) where V is vertices and E is edges, which is acceptable for the constraints.
The invariant that must hold is: when we process a node with i stops, we're guaranteed to have found the minimum cost path to that node using exactly i stops (or fewer), and we never exceed K stops in our exploration.
4. Data Structure Choice
For this problem, I'll use a combination of data structures to efficiently track the cheapest flights within K stops:
Primary Data Structures:
-
Priority Queue (Min Heap) -
PriorityQueue<int[]>with elements[city, cost, stops]- Used to always process the cheapest flight path first
- Essential for Dijkstra's algorithm variant
- Time complexity: O(log n) for insertions and deletions
- Space complexity: O(n) where n is the number of cities
-
Graph Representation -
Map<Integer, List<int[]>>where each entry is[destination, price]- Maps each city to its direct flight connections
- Allows O(1) lookup of outgoing flights from any city
- Space efficient for sparse graphs
-
Visited Tracking -
int[]array of sizen(number of cities)- Tracks minimum stops needed to reach each city
- Prevents reprocessing paths that are already suboptimal
- Space complexity: O(n)
Why These Choices:
The priority queue is crucial for maintaining the optimal path selection order, ensuring we never process a more expensive route than necessary. The graph representation allows efficient traversal of flight connections, while the visited array prevents redundant exploration by tracking the minimum stops required to reach each city.
The combination ensures we can efficiently explore paths while maintaining optimality constraints. The visited array prevents exponential growth in the search space by pruning redundant paths that exceed the optimal stop count for a given city.
Helper Structures:
- No additional helper structures needed beyond the core data structures above
- The solution uses standard Java collections (
HashMap,PriorityQueue) for clean, readable implementation
These choices balance between optimal time complexity (O((V+E) log V)) and reasonable space usage (O(V + E)), making the solution efficient for the constraints typically found in FAANG interviews.
5. Algorithm Walkthrough
Let me trace through the algorithm with a concrete example to demonstrate how it works step by step.
Example: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Step 1: Initialize data structures
distarray:[0, ∞, ∞](distance from source to each city)queue:[(0, 0, 0)](city, stops used, cost)stopsarray:[0, ∞, ∞](minimum stops to reach each city)
Step 2: Process queue element (0, 0, 0)
- Current city: 0, stops: 0, cost: 0
- Check neighbors of city 0:
[1, 2](flights [0,1,100], [0,2,500]) - Update city 1: cost = 0 + 100 = 100, stops = 1
- Update city 2: cost = 0 + 500 = 500, stops = 1
distbecomes:[0, 100, 500]stopsbecomes:[0, 1, 1]- Queue:
[(1, 1, 100), (2, 1, 500)]
Step 3: Process queue element (1, 1, 100)
- Current city: 1, stops: 1, cost: 100
- Check neighbors of city 1:
[2](flight [1,2,100]) - Update city 2: cost = 100 + 100 = 200, but this is better than existing 500
distbecomes:[0, 100, 200]- Queue:
[(2, 1, 500)]
Step 4: Process queue element (2, 1, 500)
- Current city: 2, stops: 1, cost: 500
- No outgoing flights from city 2
- Queue is now empty
Final result: dist[2] = 200
The algorithm correctly identifies that the cheapest path with at most 1 stop is 0 → 1 → 2 with cost 200, which is better than the direct path 0 → 2 with cost 500.
Edge case handling:
- When
k = 0, only direct flights are considered - The stops array ensures we don't exceed the maximum allowed stops
- If no path exists, return -1 (this is handled by the initial infinity values)
The algorithm terminates correctly because:
- We process nodes in order of increasing cost
- We maintain the constraint that we never use more than
kstops - The queue is processed in BFS fashion, ensuring optimal exploration
6. Java Solution
import java.util.*;
public class CheapestFlights {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
// Build adjacency list representation of the graph
Map<Integer, List<int[]>> graph = new HashMap<>();
for (int[] flight : flights) {
int from = flight[0];
int to = flight[1];
int price = flight[2];
graph.putIfAbsent(from, new ArrayList<>());
graph.get(from).add(new int[]{to, price});
}
// Priority queue to store {city, total_cost, stops_made}
// Sort by cost (ascending) - we want the cheapest path
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);
pq.offer(new int[]{src, 0, 0}); // {city, cost, stops}
// Track minimum stops needed to reach each city
// This helps prune paths that exceed k stops or are suboptimal
int[] minStops = new int[n];
Arrays.fill(minStops, Integer.MAX_VALUE);
while (!pq.isEmpty()) {
int[] current = pq.poll();
int city = current[0];
int cost = current[1];
int stops = current[2];
// If we've reached destination, return the cost
if (city == dst) {
return cost;
}
// Skip if we've already found a better path to this city with fewer stops
if (stops >= minStops[city]) {
continue;
}
// Update minimum stops for this city
minStops[city] = stops;
// If we've used all allowed stops, skip exploring neighbors
if (stops >= k + 1) {
continue;
}
// Explore neighbors
if (graph.containsKey(city)) {
for (int[] neighbor : graph.get(city)) {
int nextCity = neighbor[0];
int price = neighbor[1];
pq.offer(new int[]{nextCity, cost + price, stops + 1});
}
}
}
// No valid path found within k stops
return -1;
}
}
This solution uses a modified Dijkstra's algorithm with a priority queue to find the cheapest flight path from source to destination with at most k stops. The key insight is to track both cost and number of stops, and use the minimum stops array to prune suboptimal paths. The algorithm explores paths in order of increasing cost, ensuring we find the optimal solution when we first reach the destination.
7. Complexity Analysis
Time Complexity: O((E + V) × K) where E is the number of flights, V is the number of cities, and K is the maximum allowed stops.
The algorithm uses a modified BFS approach with a priority queue (or simple queue) that processes at most K levels of stops. For each level, we process all edges from the current city to its neighbors. In the worst case, we might need to process all edges up to K times, giving us O(E × K) time complexity. Additionally, we process each vertex at most K+1 times (once for each stop count), which contributes O(V × K) to the overall complexity. Since E ≥ V in most cases, the dominant term is O(E × K).
Space Complexity: O(V + E)
We use space for:
- The adjacency list representation of the graph: O(E + V)
- The queue/stack for BFS traversal: O(V) in the worst case
- The distance array: O(V)
- Additional space for tracking visited nodes or levels: O(V)
The total space complexity is O(V + E) since we're storing the graph structure and maintaining state for each vertex.
Why these bounds are correct:
The algorithm maintains a strict bound on the number of iterations through the K stops constraint. Each edge is processed at most once per stop level, and each vertex is visited at most K+1 times. The queue operations are O(1) amortized, and the adjacency list lookups are O(1) on average. The complexity matches the optimal approach for this variant of shortest path problems with bounded hops.
This solution is near-optimal for the constrained K-stops problem, as any algorithm that must consider all valid paths with at most K stops will have at least this complexity. The solution avoids the exponential blowup that would occur with a naive recursive approach, and it's more efficient than running full Dijkstra's algorithm on the expanded graph.
8. Edge Cases & Pitfalls
Empty and minimal inputs:
- Empty flights array should return -1 (no paths exist)
- Single flight should return that flight's cost if source equals destination
- If source equals destination, return 0 (no travel needed)
- If there are no flights from source, return -1
Duplicate values and repeated states:
- Multiple flights between same cities can exist, but we want the cheapest
- The same city can be visited multiple times with different costs and stop counts
- Need to track minimum cost to reach each city with at most K stops, not just first visit
Boundary conditions:
- When K = 0 (no stops allowed), only direct flights are valid
- When K is large enough to allow all possible paths, we're looking for shortest path in weighted graph
- If K is 0 but there's no direct flight, return -1
Common implementation mistakes:
- Using a simple Dijkstra's without tracking stop count - this will find shortest path but not necessarily within K stops
- Not properly handling the "at most K stops" constraint - some implementations treat it as exactly K stops
- Not tracking minimum cost per city with stop constraints - can lead to exploring suboptimal paths unnecessarily
- Using Integer.MAX_VALUE for cost tracking instead of proper initialization, leading to overflow issues
- Forgetting to check if source equals destination at the beginning - this should return 0 immediately
Implementation-specific pitfalls:
- Not clearing or properly resetting state in test scenarios
- Using incorrect queue ordering (should prioritize by cost, not stops)
- Assuming flights are bidirectional when they're actually directed
- Not handling the case where a city is unreachable within K stops - should return -1, not 0 or some other value
9. Alternative Approaches
There are several alternative approaches to solving this problem, each with different trade-offs:
1. Bellman-Ford Algorithm (Modified) Instead of using a priority queue, we can use a modified Bellman-Ford approach that limits iterations to K+1 steps. This approach processes all edges up to K+1 times, which naturally limits the number of stops. The time complexity is O((K+1) × E) where E is the number of edges. This approach is more intuitive but potentially less efficient than our Dijkstra-based solution when K is small.
2. DFS with Memoization We could use depth-first search with memoization, storing the minimum cost to reach each city with a specific number of stops. However, this approach is more complex to implement correctly and can lead to exponential time complexity in worst-case scenarios due to overlapping subproblems. It also requires careful handling of cycles and state management.
3. BFS with Stop Counting A breadth-first search approach that tracks the number of stops alongside the cost. At each level, we process all cities reachable with exactly one more stop than the previous level. This ensures we never exceed K stops and naturally explores paths in increasing cost order. The space complexity is higher as we need to maintain the queue with stop counts.
4. Dynamic Programming with State We can define dp[i][k] as the minimum cost to reach city i using exactly k stops. This creates a 2D DP table where we iterate through stop counts and update costs accordingly. The time complexity becomes O((K+1) × N) where N is the number of cities. This approach is more explicit about the state transitions but uses more space.
The chosen solution using Dijkstra with a priority queue is preferred because it provides optimal time complexity O((K+1) × E + V log V) and is more intuitive to implement correctly. The alternative approaches either have higher time complexity or are more error-prone in their implementation.
// Example of Bellman-Ford approach (not implemented in final solution)
/*
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;
// Run for k+1 iterations to allow at most k stops
for (int i = 0; i <= k; i++) {
int[] tempDist = dist.clone();
for (int[] flight : flights) {
int from = flight[0];
int to = flight[1];
int cost = flight[2];
if (dist[from] != Integer.MAX_VALUE) {
tempDist[to] = Math.min(tempDist[to], dist[from] + cost);
}
}
dist = tempDist;
}
return dist[dst] == Integer.MAX_VALUE ? -1 : dist[dst];
}
*/
10. Test Cases
public class CheapestFlightsTestCases {
public static void main(String[] args) {
// Test Case 1: Basic case with valid solution
// Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
// Expected: 200
int n1 = 3;
int[][] flights1 = {{0,1,100},{1,2,100},{0,2,500}};
int src1 = 0, dst1 = 2, k1 = 1;
// Test Case 2: No valid path within K stops
// Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
// Expected: -1
int n2 = 3;
int[][] flights2 = {{0,1,100},{1,2,100},{0,2,500}};
int src2 = 0, dst2 = 2, k2 = 0;
// Test Case 3: Single stop path is cheapest
// Input: n = 4, flights = [[0,1,1],[1,2,1],[2,3,1]], src = 0, dst = 3, k = 1
// Expected: -1 (no path with at most 1 stop)
int n3 = 4;
int[][] flights3 = {{0,1,1},{1,2,1},{2,3,1}};
int src3 = 0, dst3 = 3, k3 = 1;
// Test Case 4: Multiple paths with same destination
// Input: n = 4, flights = [[0,1,1],[1,2,1],[2,3,1],[0,2,5]], src = 0, dst = 3, k = 2
// Expected: 3 (0->1->2->3 with cost 1+1+1=3)
int n4 = 4;
int[][] flights4 = {{0,1,1},{1,2,1},{2,3,1},{0,2,5}};
int src4 = 0, dst4 = 3, k4 = 2;
// Test Case 5: Self loop and multiple paths
// Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500],[2,1,50]], src = 0, dst = 1, k = 2
// Expected: 150 (0->2->1 with cost 500+50=550, but 0->1 is 100, and 0->2->1 is 500+50=550)
// Actually, 0->1 is 100, and 0->2->1 is 500+50=550, so 100 is better
int n5 = 3;
int[][] flights5 = {{0,1,100},{1,2,100},{0,2,500},{2,1,50}};
int src5 = 0, dst5 = 1, k5 = 2;
// Test Case 6: Empty flights array
// Input: n = 3, flights = [], src = 0, dst = 2, k = 1
// Expected: -1
int n6 = 3;
int[][] flights6 = {};
int src6 = 0, dst6 = 2, k6 = 1;
// Test Case 7: Same source and destination
// Input: n = 3, flights = [[0,1,100],[1,2,100]], src = 0, dst = 0, k = 1
// Expected: 0 (no travel needed)
int n7 = 3;
int[][] flights7 = {{0,1,100},{1,2,100}};
int src7 = 0, dst7 = 0, k7 = 1;
}
}
Sample Test Cases:
-
Basic Valid Path:
- Input:
n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 - Expected:
200(via intermediate stop at city 1) - Tests the core functionality with valid path within K stops
- Input:
-
No Valid Path:
- Input:
n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 - Expected:
-1(no path with zero stops) - Tests boundary condition where no stops allowed
- Input:
-
No Path Within Stop Limit:
- Input:
n = 4, flights = [[0,1,1],[1,2,1],[2,3,1]], src = 0, dst = 3, k = 1 - Expected:
-1(path requires 2 stops but only 1 allowed) - Tests the stop constraint enforcement
- Input:
-
Multiple Path Options:
- Input:
n = 4, flights = [[0,1,1],[1,2,1],[2,3,1],[0,2,5]], src = 0, dst = 3, k = 2 - Expected:
3(optimal path is 0->1->2->3) - Tests multiple valid paths and cost comparison
- Input:
-
Complex Path with Reversals:
- Input:
n = 3, flights = [[0,1,100],[1,2,100],[0,2,500],[2,1,50]], src = 0, dst = 1, k = 2 - Expected:
100(direct path is cheaper than 0->2->1) - Tests handling of reverse edges and multiple route options
- Input:
-
Empty Flight Network:
- Input:
n = 3, flights = [], src = 0, dst = 2, k = 1 - Expected:
-1(no flights available) - Tests edge case with no flight data
- Input:
-
Same Source/Destination:
- Input:
n = 3, flights = [[0,1,100],[1,2,100]], src = 0, dst = 0, k = 1 - Expected:
0(no travel needed) - Tests edge case where source equals destination
- Input:
These test cases cover all major scenarios: valid paths, constraint violations, boundary conditions, and edge cases that help ensure robust solution implementation.
11. Final Summary
The core idea is to find the cheapest flight path from source to destination with at most K stops using a modified Dijkstra's algorithm with a focus on stop count rather than distance. This solution works efficiently by maintaining the minimum cost to reach each city with exactly i stops, ensuring we don't explore paths that exceed our stop constraint. The approach is optimal with O((K+1) × (V + E)) time complexity where V is vertices and E is edges, making it well-suited for the constrained stop problem.