Skip to main content

Cheapest Flights Within K Stops

In this page, we will solve the Cheapest Flights Within K Stops problem using two different approaches: Breadth First Search and Depth First Search technique. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more.

Problem Description​

There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.

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.

Examples​

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

Example 2:

Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200

Constraints​

  • 1 <= n <= 100
  • 0 <= flights.length <= (n * (n - 1) / 2)
  • flights[i].length == 3
  • 0 <= fromi, toi < n
  • fromi != toi
  • 1 <= pricei <= 104
  • 0 <= src, dst, k < n
  • src != dst
  • There will not be any multiple flights between two cities.

Solution for Cheapest Flights Within K Stops Problem​

Intuition and Approach​

To solve the problem of finding the minimum cost to reach a destination from a source with a restriction on the number of stops, we can use Dijkstra’s Algorithm with a key modification. Instead of prioritizing minimum distance, we prioritize the minimum number of stops in the priority queue. This ensures that we explore paths with fewer stops, which helps us avoid premature termination of the algorithm due to exceeding the stop limit.

However, since the number of stops increases monotonically (by 1 each iteration), we don't actually need a priority queue. A simple queue is sufficient because we always pop the element with the lesser number of stops first, thus eliminating the extra log(N) complexity associated with insertion and deletion in a priority queue. This change improves the algorithm's efficiency.

To solve the problem, create an adjacency list and initialize a queue to store pairs. Set up a distance array with large values to mark unvisited nodes and set the source node's distance to 0. Push the source node into the queue with distance 0 and 0 stops. Process the queue by popping elements, and for each adjacent node, update the distance and push it back into the queue if the current distance is less and the stop count is below K. Continue until the queue is empty. If the destination is reached within the required stops, return the distance; otherwise, return -1 if no valid path exists.

Codes in Different Languages​

Written by @aryan-1309
 var findCheapestPrice = function(n, flights, src, dst, K) {
let graph = {} // {from: { to: price }, {to: price}}

for (let [source, destination, price] of flights){
if (!graph.hasOwnProperty(source)) {
graph[source] = {}
}
graph[source][destination] = price
}

let queue = [[0,src,0]]

while (queue.length ) {
let [price, city, connections] = queue.shift()
if (city == dst) return price
if (connections > K) continue

if (graph[city]) {
for (let nextStops in graph[city]) {
let cost = graph[city][nextStops]
queue.push([cost + price, nextStops, connections + 1])
}
}
queue.sort((a,b) => a[0]-b[0])

}
return -1
}

Complexity Analysis​

  • Time Complexity: O(N)O(N)
  • Space Complexity: O(∣E∣+∣V∣)O(|E|+|V|)
  • Where N is the Number of flights / Number of edges..
  • Where E = Number of edges (flights.size()) and V = Number of Airports.

References​