KatInterview

803. Cheapest Flights Within K Stops

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the cheapest flight from a source src to a destination dst with at most k stops. This can be modeled as a shortest path problem on a weighted directed graph. However, there's an additional constraint on the number of edges in the path, which is at most k+1 (since k stops means k intermediate cities).

Solution

Cheapest Flights Within K Stops in Python

class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
        # prices[i] stores the minimum cost to reach city i.
        prices = [float('inf')] * n
        prices[src] = 0
        
        # We can make at most k stops, which means at most k+1 flights.
        # So we iterate k+1 times (for paths with 1 to k+1 edges).
        for i in range(k + 1):
            # Use a temporary array to store prices for the current iteration.
            # This is crucial because we need to use the prices from the previous iteration (i-1 stops)
            # to calculate the prices for the current iteration (i stops).
            temp_prices = prices[:]
            
            for from_city, to_city, price in flights:
                # If the source city of the flight is reachable in the previous step.
                if prices[from_city] != float('inf'):
                    # Update the destination city's price if we find a cheaper path.
                    temp_prices[to_city] = min(temp_prices[to_city], prices[from_city] + price)
            
            # Update prices for the next iteration.
            prices = temp_prices
            
        # The result is the minimum price to the destination city.
        # If it's still infinity, it means the destination is not reachable.
        return prices[dst] if prices[dst] != float('inf') else -1

Cheapest Flights Within K Stops in Java

class Solution {
    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
        // prices[i] stores the minimum cost to reach city i.
        long[] prices = new long[n];
        Arrays.fill(prices, Long.MAX_VALUE);
        prices[src] = 0;

        // We can make at most k stops, which means at most k+1 flights.
        // So we iterate k+1 times (for paths with 1 to k+1 edges).
        for (int i = 0; i <= k; i++) {
            // Use a temporary array to store prices for the current iteration.
            // This is crucial because we need to use the prices from the previous iteration (i-1 stops)
            // to calculate the prices for the current iteration (i stops).
            long[] tempPrices = Arrays.copyOf(prices, n);
            for (int[] flight : flights) {
                int from = flight[0];
                int to = flight[1];
                int price = flight[2];

                // If the source city of the flight is reachable in the previous step.
                if (prices[from] != Long.MAX_VALUE) {
                    // Update the destination city's price if we find a cheaper path.
                    tempPrices[to] = Math.min(tempPrices[to], prices[from] + price);
                }
            }
            // Update prices for the next iteration.
            prices = tempPrices;
        }

        // The result is the minimum price to the destination city.
        // If it's still Long.MAX_VALUE, it means the destination is not reachable.
        return prices[dst] == Long.MAX_VALUE ? -1 : (int) prices[dst];
    }
}

Cheapest Flights Within K Stops in C++

class Solution {
public:
    int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
        // prices[i] stores the minimum cost to reach city i.
        vector<long> prices(n, LONG_MAX);
        prices[src] = 0;

        // We can make at most k stops, which means at most k+1 flights.
        // So we iterate k+1 times (for paths with 1 to k+1 edges).
        for (int i = 0; i <= k; ++i) {
            // Use a temporary array to store prices for the current iteration.
            // This is crucial because we need to use the prices from the previous iteration (i-1 stops)
            // to calculate the prices for the current iteration (i stops).
            vector<long> temp_prices = prices;
            for (const auto& flight : flights) {
                int from = flight[0];
                int to = flight[1];
                int price = flight[2];
                
                // If the source city of the flight is reachable in the previous step.
                if (prices[from] != LONG_MAX) {
                    // Update the destination city's price if we find a cheaper path.
                    temp_prices[to] = min(temp_prices[to], prices[from] + price);
                }
            }
            // Update prices for the next iteration.
            prices = temp_prices;
        }

        // The result is the minimum price to the destination city.
        // If it's still LONG_MAX, it means the destination is not reachable.
        return prices[dst] == LONG_MAX ? -1 : prices[dst];
    }
};

Cheapest Flights Within K Stops in TypeScript

function findCheapestPrice(n: number, flights: number[][], src: number, dst: number, k: number): number {
    // prices[i] stores the minimum cost to reach city i.
    let prices = new Array(n).fill(Infinity);
    prices[src] = 0;

    // We can make at most k stops, which means at most k+1 flights.
    // So we iterate k+1 times (for paths with 1 to k+1 edges).
    for (let i = 0; i <= k; i++) {
        // Use a temporary array to store prices for the current iteration.
        // This is crucial because we need to use the prices from the previous iteration (i-1 stops)
        // to calculate the prices for the current iteration (i stops).
        const tempPrices = [...prices];

        for (const flight of flights) {
            const [from, to, price] = flight;
            // If the source city of the flight is reachable in the previous step.
            if (prices[from] !== Infinity) {
                // Update the destination city's price if we find a cheaper path.
                tempPrices[to] = Math.min(tempPrices[to], prices[from] + price);
            }
        }
        // Update prices for the next iteration.
        prices = tempPrices;
    }

    // The result is the minimum price to the destination city.
    // If it's still Infinity, it means the destination is not reachable.
    return prices[dst] === Infinity ? -1 : prices[dst];
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.