Cheapest Flights Within K Stops
Updated
Problem statement
There are n cities numbered from 0 through n - 1.
Each row [from, to, price] in flights describes a directed flight from city from to city to that costs price.
Return the lowest price of a route from src to dst that uses at most k intermediate stops. Equivalently, the route may use at most k + 1 flights. Return -1 if no such route exists.
Function
findCheapestPrice(n: int, flights: int[][], src: int, dst: int, k: int) → intExamples
Example 1
n = 4flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]]src = 0dst = 3k = 1return = 700The cheapest valid route is 0 -> 1 -> 3, which has one intermediate stop and costs 100 + 600 = 700. The cheaper route through cities 1 and 2 uses two stops and is therefore invalid.
Example 2
n = 3flights = [[0,1,100],[1,2,100],[0,2,500]]src = 0dst = 2k = 1return = 200The route 0 -> 1 -> 2 uses one stop and costs 200, which is less than the direct flight cost of 500.
Example 3
n = 3flights = [[0,1,100],[1,2,100],[0,2,500]]src = 0dst = 2k = 0return = 500With no intermediate stops allowed, only the direct flight from city 0 to city 2 is valid, so the answer is 500.
Constraints
2 <= n <= 1000 <= flights.length <= n * (n - 1) / 2flights[i].length == 30 <= flights[i][0], flights[i][1] < nflights[i][0] != flights[i][1]1 <= flights[i][2] <= 10^4- There is at most one directed flight from one city to another.
0 <= src, dst, k < nsrc != dst
More InMobi Online Assessment questions
- Validate a Bracket SequenceOA · Seen Oct 2026
- Count Substrings Matching with One Adjacent SwapOA · Seen Oct 2026
- Maximum Subarray with Start and End WindowsOA · Seen Oct 2026
- Minimum Service Cold StartsOA · Seen Oct 2026
- Range Maximum Subarray Sum QueriesOA · Seen Oct 2026
- Connected Components with Divisor ThresholdOA · Seen Aug 2026
- Maximize Impression ValueOA · Seen Aug 2026
- Supply Path OptimizationOA · Seen Aug 2026
- Delivery ServiceOA · Seen Jun 2026
- Shared InterestOA · Seen Jun 2026
Similar questions at other companies
- Cities on Shortest Delivery RoutesMathWorks · OAMathWorks interview questions
- All-Pairs Shortest PathsMorgan Stanley · OA · ONSITE INTERVIEWMorgan Stanley interview questions
- Drone Delivery with Battery Swap StationsCisco · OACisco interview questions
- Cheapest Flight with Its PathAirbnb · OA · PHONE SCREEN · ONSITE INTERVIEWAirbnb interview questions
- Shortest Paths in a Nonnegative Directed GraphNation with NaMo · PHONE SCREEN
- Cheapest Flights Within K StopsGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Minimum Path Cost with Edge DiscountsSkyscanner · ONSITE INTERVIEWSkyscanner interview questions
- Maximum Gain on a Budgeted Returning WalkNVIDIA · ONSITE INTERVIEWNVIDIA interview questions
- Delivery Management SystemAkuna Capital · OAAkuna Capital interview questions
- Count Routes Through Four Shop TypesOpenAI · OAOpenAI interview questions