Cheapest Flight Itinerary with a Limit on Layovers
Last updated: November 29, 2026
Quick Overview
Given flights (from, to, price) between n airports, a source, a destination, and a maximum number of stops k, return the cheapest total price using at most k intermediate stops, or -1.
0
0
0 solved
Given flights (from, to, price) between n airports, a source, a destination, and a maximum number of stops k, return the cheapest total price using at most k intermediate stops, or -1.
Framed around Google Flights, this question deliberately breaks plain Dijkstra by adding a hop limit. The interviewer is checking whether you notice that the cheapest path can use too many stops and pick a hop-bounded Bellman-Ford or a state-expanded search.
What the Interviewer Expects
- Explains why vanilla Dijkstra on cost alone can return an invalid itinerary
- Uses k + 1 rounds of Bellman-Ford relaxation
- Relaxes from a copy of the previous round to avoid chaining multiple edges in one round
- Returns -1 when unreachable within the limit
- Gives O(k * E) time and discusses Dijkstra on (node, stops) states
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Also minimize total travel time as a tie-breaker.
- Return the actual itinerary, not just the price.
- Prices depend on departure date; how does the graph model change?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- n airports 0..n-1, directed priced flights, source
src, destinationdst, stop limit k. - At most k stops means at most k + 1 flights.
- Output: minimal cost or -1. src equal to dst costs 0....
High-Level Design
Let best[v] after round r be the cheapest cost to reach v using at most r flights. Start with best[src] = 0. Run k + 1 rounds; in each, copy best to nxt and for every flight (u, v, p) with `be...