Cheapest Flights Within K Stops

Algorithms
Medium
Amazon
25.2K views

Given $n$ cities and flights, find the cheapest price from a source to a destination with at most $k$ stops. Use a modification of BFS or Bellman-Ford (or Dijkstra with a stop counter).

Why Interviewers Ask This

Amazon asks this variation of the shortest path problem to evaluate a candidate's ability to modify standard algorithms under constraints. They specifically test your understanding of trade-offs between BFS, Dijkstra, and Bellman-Ford when a hop limit exists. The interviewer wants to see if you can handle state-space expansion where the 'visited' set must include both node identity and current stop count, reflecting Amazon's focus on solving complex logistical routing problems efficiently.

How to Answer This Question

1. Clarify Constraints: Immediately confirm if k represents stops (edges minus one) or total edges, and verify if the graph is directed or weighted with negative values. 2. Select Algorithm: Propose Modified BFS for unweighted logic or Dijkstra with a priority queue storing [cost, u, stops]. Explain why Bellman-Ford might be too slow for large inputs but valid for small graphs. 3. Define State: Explicitly state that standard visited arrays are insufficient; you need to track the minimum cost to reach a node with exactly 's' stops, as a higher-cost path with fewer stops might yield a better final result. 4. Implement Logic: Describe iterating through neighbors, updating costs only if the new price is lower AND the stop count remains within k. 5. Optimize and Discuss: Mention pruning branches where stops exceed k and discuss time complexity O(E*K) versus O(E log V), highlighting how this scales for Amazon's massive flight networks.

Key Points to Cover

  • Explicitly defining the state as (node, stops_used) rather than just (node)
  • Justifying the choice between Modified Dijkstra and BFS based on edge weights
  • Handling the base case where the destination is unreachable within k stops
  • Demonstrating awareness that a more expensive path with fewer stops is valuable
  • Correctly interpreting 'k stops' as k+1 edges in the implementation

Sample Answer

To solve the cheapest flights within K stops problem, I would treat this as a constrained shortest path search. Unlike standard Dijkstra which only tracks the minimum cost to a node, here we must track the minimum cost for each specific number of stops used. I propose using a modified Dijkstra approach where the priority queue stores tuples of [current_cost, city_index, stops_remaining]. First, I initialize the distance array with infinity, except for the source which is zero. When extracting a node from the queue, if stops_remaining is greater than zero, I iterate through its neighbors. For each neighbor, I calculate the new total cost. Crucially, I only push this neighbor to the queue if the new cost is strictly less than what was previously recorded for that specific stop count. This ensures we explore paths that might be initially expensive but become cheaper due to the stop constraint. For example, if flying direct costs $500 with 0 stops, but a route via one hub costs $300, my algorithm will correctly identify the $300 option even if it appears later in the traversal. If the destination is unreachable within k stops, I return -1. This approach balances efficiency with the strict constraint, running in O(E * K) time, which is optimal for this specific variation compared to full Bellman-Ford iterations.

Common Mistakes to Avoid

  • Using a standard visited array that marks a node as done after the first visit, ignoring potentially cheaper paths with different stop counts
  • Confusing the definition of 'stops' with 'edges', leading to an off-by-one error in the loop condition
  • Implementing a recursive DFS solution without memoization, causing exponential time complexity
  • Failing to prune the search space when the stop counter reaches zero, resulting in TLE on large inputs

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 73 Amazon questions