Advertisement

Cheapest Flights Within K Stops - LeetCode 787 Solution

Cheapest Flights Within K Stops - Complete Solution Guide

Cheapest Flights Within K Stops is LeetCode problem 787, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

There are n cities connected by some number of flights. You are given an array flights where flights[i] = [from i , to i , price i ] indicates that there is a flight from city from i to city to i with cost price i . You are also given three integers src , dst , and k , return the cheapest price from src to dst with at most k stops. If there is no such route, return -1 . Example 1: Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 Output: 700 Exp

Detailed Explanation

The problem asks us to find the cheapest price to travel from a source city `src` to a destination city `dst` within a maximum of `k` stops, given a list of flights represented as `flights[i] = [from_i, to_i, price_i]`. We need to return the minimum cost, or -1 if no such route exists within the given constraints. The number of cities is `n`. Crucially, a 'stop' represents visiting an intermediate city. A direct flight from `src` to `dst` involves zero stops.

Solution Approach

The provided solution uses a dynamic programming approach based on the Bellman-Ford algorithm to find the shortest path with a limited number of edges (stops). We maintain an array `prices` that stores the minimum cost to reach each city from the source city. We iterate `k+1` times, each time representing one more allowed stop. In each iteration, we update the `prices` array by considering all possible flights. A crucial part is to create a temporary copy of the `prices` array (`temp_prices`) before updating, to ensure that we only consider paths with at most `i` stops in the `i`-th iteration. This ensures correctness.

Step-by-Step Algorithm

  1. Step 1: Initialize an array `prices` of size `n` with infinity (or MAX_VALUE) for all cities except the source city, which is initialized to 0.
  2. Step 2: Iterate `k+1` times (representing the maximum number of stops allowed).
  3. Step 3: In each iteration, create a temporary copy `temp_prices` of the `prices` array. This is critical to avoid incorrect updates during the iteration.
  4. Step 4: Iterate through the `flights` array. For each flight `[u, v, p]`, check if `prices[u]` is not infinity. If it's not, check if `prices[u] + p` (the cost to reach city `u` plus the cost of the flight from `u` to `v`) is less than `temp_prices[v]` (the current minimum cost to reach city `v`).
  5. Step 5: If `prices[u] + p` is less than `temp_prices[v]`, update `temp_prices[v]` to `prices[u] + p`.
  6. Step 6: After iterating through all flights, update `prices` with the values from `temp_prices`. This completes one iteration, representing paths with at most `i` stops.
  7. Step 7: After the loop finishes (after `k+1` iterations), check if `prices[dst]` is still infinity. If it is, it means there is no path from `src` to `dst` within `k` stops, so return -1.
  8. Step 8: Otherwise, return `prices[dst]`, which represents the cheapest price to reach `dst` from `src` within `k` stops.

Key Insights

  • Insight 1: The core idea is to relax the edges of the graph representing the flight network `k+1` times. This relaxation process involves iterating through all flights and updating the minimum cost to reach the destination of each flight, considering the number of stops allowed.
  • Insight 2: The use of dynamic programming with a temporary array to store the updated prices after each iteration is essential. This prevents updating a price based on a price that has already been updated in the same iteration, which would violate the stop constraint.
  • Insight 3: Handling the 'no path' scenario by returning -1 when the minimum price to reach the destination remains infinity (or MAX_VALUE) after all iterations is crucial.

Complexity Analysis

Time Complexity: O(K * E)

Space Complexity: O(N)

Topics

This problem involves: Dynamic Programming, Depth-First Search, Breadth-First Search, Graph, Heap (Priority Queue), Shortest Path.

Companies

Asked at: Airbnb, Cloudera, Coupang, DE Shaw, MakeMyTrip, Snap, Snowflake, Stripe.