The problem:

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.

My solution, implemented in JavaScript:

var findCheapestPrice = function(n, flights, src, dst, k) {
    // generate a graph
    let map = new Map();
    for(let i=0; i<flights.length; i++) {
        const [orig, des, cost] = flights[i];
        const temp = map.get(orig) || []
        temp.push([des, cost]);
        map.set(orig, temp);
    // start from the source with cost 0
    // [cost, city, available stops]
    let queue = [[0,src,k+1]]
    while(queue.length > 0) {
        const [cost, city, stops] = queue.shift();
        if(city === dst)    return cost;    // Get in the destination
        // still have available stops
        if(stops > 0) {
            const possibleFlights = map.get(city) || [];
            for(const pf of possibleFlights) {
                // current cost + flight cost
                // decrement stops (one stop to this airport)
                queue.push([cost+pf[1], pf[0], stops-1]);
            // Sort by the cheapest next flight (Heap?)
            queue.sort((a,b) => a[0]-b[0]);
    // couldn't find a path
    return -1;

It works just fine with the basic case tests, but it fails with time limit exceed for the test case below. Is there a way to improve the code?

  • \$\begingroup\$ The code doesn't look correct. If there is a direct flight from src to dst, it will be returned at the very first iteration. Indirect flights (which could be cheaper) are not considered. \$\endgroup\$
    – vnp
    Jul 1, 2021 at 22:32
  • \$\begingroup\$ @vnp I don't think so, because he is sorting the queue by price as far as I understand. \$\endgroup\$
    – Blaž Mrak
    Jul 2, 2021 at 11:07
  • \$\begingroup\$ @BlažMrak yes, the sorting makes the code work, but too slow \$\endgroup\$ Jul 2, 2021 at 15:42
  • \$\begingroup\$ @myTest532myTest532 what do the inputs for the test mean? It would be helpful if you named them. \$\endgroup\$
    – Blaž Mrak
    Jul 2, 2021 at 16:41
  • \$\begingroup\$ The test inputs are in the same order as the function arguments. \$\endgroup\$ Jul 2, 2021 at 17:46

1 Answer 1



I have refactored your code to be more understandable. I have mainly extracted what you commented into functions and changed what you had in tuples into objects.

Here is the result:

function generatePossibleFlightsFromCities(flights) {
  const map = {}

  for (let i = 0; i < flights.length; i++) {
    const [origin, destination, cost] = flights[i]
    const destinationsFromOrigin = map[origin] || []
    map[origin] = destinationsFromOrigin

  return map

function initiateQueue(src, k) {
  return [{
    cost: 0,
    city: src,
    stops: k + 1

function insertIntoTheQueue(queue, cost, stops, possibleFlight) {
  const totalCost = cost + possibleFlight.cost

    cost: totalCost,
    city: possibleFlight.destination,
    stops: stops - 1

function noMoreStops(stops) {
  return stops === 0

function cameToDestination(city, dst) {
  return city === dst

function notEmpty(queue) {
  return queue.length > 0

function findCheapestFlight(queue, possibleFlightsFromCities, destination) {
  while (notEmpty(queue)) {
    const {
    } = queue.shift();

    if (cameToDestination(city, destination)) return cost;
    if (noMoreStops(stops)) continue

    const possibleFlights = possibleFlightsFromCities[city]
    for (const possibleFlight of possibleFlights) {
      insertIntoTheQueue(queue, cost, stops, possibleFlight)

    queue.sort((a, b) => a.cost - b.cost);

  return -1

const findCheapestPrice = function(n, flights, src, dst, k) {
  let possibleFlightsFromCities = generatePossibleFlightsFromCities(flights)
  let queue = initiateQueue(src, k)

  return findCheapestFlight(queue, possibleFlightsFromCities, dst);

This code still has the same problem, but is more readable and easier to understand. The problem still remains as the program still takes too much time.


You could have tried with the heap, but I do not think it would have solved your problem. The problem is that you simply have too much items in your queue. If you look at your queue you will see something like this:

[{city: 0, cost: 150, stops: 3}, 
{city: 0, cost: 230, stops: 5}, 
{city: 0, cost: 270, stops: 5}, 

Notice, there is nothing wrong with the first one, but look at the second and third one. They stopped exactly the same amount of times, but the second one came there cheaper. This leads to the conclusion that no matter what the third one will always be more expensive, so we can get rid of it - meaning we shouldn't insert it in the queue in the first place. Basically we do not want to try to go somewhere if we can arrive there cheaper by some other path.

The only thing that changes is how we insert the possible flights into the queue:

function cheaperPathToDestinationExists(queue, destination, cost, stops) {
  return queue.some(item => item.city === destination && item.stops === stops && item.cost < cost)

function insertIntoTheQueue(queue, cost, stops, possibleFlight) {
  const totalCost = cost + possibleFlight.cost
  if (cheaperPathToDestinationExists(queue, possibleFlight.destination, totalCost, stops - 1)) return

    cost: totalCost,
    city: possibleFlight.destination,
    stops: stops - 1

The solution isn't perfect. There are still some branches that you can cut, but I will leave this up to you to figure out. Also, it is more of a Stack Overflow/Software Engineering question and not a Code Review one.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.