How to find the cheapest flight within K stops
StripeSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to find the shortest path in a weighted graph under a specific constraint on the number of edges (stops).
Problem Statement
You are given a list of flights, where each flights[i] = [from, to, price]. You are also given three integers: n (number of cities), src (starting city), dst (destination city), and k (the maximum number of stops allowed).
Your task is to return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.
Constraints
1 <= n <= 1000 <= flights.length <= n * (n - 1) / 20 <= from, to, src, dst < n0 <= price <= 10,0000 1 -> 3 costs 100 + 600 = 700. The route 0 -> 1 -> 2 -> 3 costs 100 + 100 + 200 = 400, but that uses 2 stops, exceeding the limitk=1`.
Function Signature
def findCheapestPrice(n: int, flights: list[list[int]], src: int, dst: int, k: int) -> int:
Hints
Hint 1
Consider this as a shortest path problem in a graph where edge weights are flight prices.
Hint 2
Standard Dijkstra's algorithm might fail here because the constraint is on the number of edges, not just the total cost.
Hint 3
Think about using dynamic programming or a modified Bellman-Ford approach where the state tracks the number of stops taken.
Follow-up questions
- How would your approach change if you needed to track the actual path taken in addition to the cost?
- What is the time and space complexity of your solution, and how does it scale with a very large number of cities?
- How would you modify the algorithm if there were a time-of-day constraint for each flight?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.