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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

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
Bellman-Ford
Graphs
Dynamic Programming
Shortest Path
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample Answer
Requirements
  • n airports 0..n-1, directed priced flights, source src, destination dst, 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...


Submit Your Answer
Markdown supported