Cheapest flights within K stops
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Stripe's technical phone screen and at Uber, last asked Feb 2026. It tests graphs, shortest path and dynamic programming.
There are n cities, numbered 0 to n - 1, and a list of one-way flights (from, to, price). Given a source, a destination and an integer k, return the lowest total price of a trip from the source to the destination that makes at most k stops in between, or -1 if no such trip exists.
Interface
Unless you agree on a different interface with the interviewer, assume:
cheapest_price(n: int, flights: list[tuple[int, int, int]], src: int, dst: int, k: int) -> int
Example
flights = [(0, 1, 100), (1, 2, 100), (2, 3, 100), (0, 2, 500), (1, 3, 600)]
cheapest_price(4, flights, 0, 3, 0) -> -1 # no direct flight
cheapest_price(4, flights, 0, 3, 1) -> 600 # 0 -> 2 -> 3 (0 -> 1 -> 3 costs 700)
cheapest_price(4, flights, 0, 3, 2) -> 300 # 0 -> 1 -> 2 -> 3
Constraints
-
1 <= n <= 100, up ton * (n - 1) / 2flights, prices from 1 to 10^4,0 <= k < n. - No duplicate flights;
src != dst.
Clarifying questions
- Is
kthe number of stops (intermediate cities) or the number of flights? - Can prices be zero or negative?
- Should I return the route as well as the price?
- How large can
nand the number of flights get?
What a strong answer covers
- Why plain Dijkstra is wrong here: the cheapest path to a city may use too many stops, while a dearer one with fewer stops leads to the answer.
- Bellman-Ford limited to
k + 1rounds, copying the distance array each round so one round adds only one flight: O(k * E) time, O(n) space. - Or BFS by level, or Dijkstra over
(city, stops used)states, with their costs. - Tests: no route,
k = 0, a cheap route with too many stops, cycles.
Follow-ups
- Return the cheapest itinerary itself, not just its price.
- Minimize price and break ties by the number of stops.
- Flights have departure and arrival times, and a connection needs at least 45 minutes.
Where it's asked
- Stripe · Technical phone screen · Last asked Feb 202660 min · One realistic task in parts, in a project editor (CoderPad project mode or HackerRank Projects) with several files and tests
- Uber · Technical phone screen · Last asked Dec 202560 min · One medium problem with a follow-up, or two short ones; sometimes object-oriented design
What it tests
graphs · shortest path · dynamic programming
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.

