Find cheapest flight with at most K stops
UberSoftware Engineer · Technical ScreenLast updated
This question evaluates graph algorithm proficiency and problem-modeling skills, specifically working with directed weighted graphs to optimize path cost under a constraint on intermediate stops.
Problem
You are given a directed weighted graph representing flights between cities.
Inputs
- An integer
n: number of cities, labeled0..n-1. - A list
flights, where each element is[from, to, price]meaning there is a flight from cityfromto citytothat costsprice. - Two integers
srcanddst: the start and destination cities. - An integer
K: the maximum number of stops allowed, where a stop is an intermediate city betweensrcanddst. - Equivalently, you may take at most
K+1flights (edges).
Output
Return the minimum total cost to travel from src to dst using at most K stops. If it is not possible, return -1.
Notes / Clarifications
- You may assume all
pricevalues are non-negative integers. - The route must follow the directed edges as given in
flights.
Example
n = 4flights = [[0,1,100],[1,2,100],[2,3,100],[0,3,500]]src = 0, dst = 3, K = 1
The cheapest valid route is 0 -> 1 -> 2 -> 3 is not allowed (2 stops), so the answer is 500 via 0 -> 3.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.