mediumAdvanced GraphsAmazonFacebook
Budget Flight Finder
A budget traveler finds the cheapest ticket chain from src to dst using at most k layovers.
Given n cities, directed flights with prices, src, dst, and k, return the cheapest price with at most k stops. -1 if no such route.
Choose approach
0
1
2
1/4
Narrationstep 1 of 4
Bellman-Ford limited to 2 rounds (≤ 1 stops).
Variables
src=0
dst=2
k=1
How to think about it
- 'At most k stops' = at most k+1 edges = k+1 Bellman-Ford rounds.
- Cloning prevents a single round from using more than one new edge.
- Dijkstra variants exist but require augmented state (city, stops_used).
Edge cases to catch in interview
- Direct flight within k stops -> that price.
- No reachable route under k stops -> -1.
Examples
Example 1
500{"n":3,"flights":[[0,1,100],[1,2,100],[0,2,500]],"src":0,"dst":2,"k":0}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed