Problem 787

Abstract / Summary

Find the minimum cost to travel between two cities with at most k stops included in the journey.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0787.py

class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
        # from => to = price
        all = defaultdict(dict)
        for f in flights:
            all[f[0]][f[1]] = f[2]

        seen = {}                  # only visit a city again if we need less stops to get there

        schedule = [ (0, 0, src) ] # heap (total price, stops, city)
        while schedule:
            total, stops, city = heappop(schedule)

            # yeah ...
            if city == dst:
                return total

            seen[city] = stops

            # continue flight
            for next in all[city]:
                if stops <= k and (next not in seen or seen[next] > stops):
                    price = all[city][next]
                    heappush(schedule, (total + price, stops + 1, next))

        return -1
26 lines | 899 bytes | submitted October 6, 2023 | GitHub   29% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 42% (2+ million submissions).

Typical patterns to solve this problem:
  • Breadth First Search
  • Depth First Search
  • Dynamic Programming
  • Graph Theory
  • Heap (Priority Queue)
  • Shortest Path
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation solves the “cheapest price with at most k stops” problem by exploring flight connections with a priority queue. It builds an adjacency map from the raw flight list, then performs a best-first search that expands the cheapest partial routes first while respecting the stop limit. The algorithm stops as soon as the destination city is dequeued, guaranteeing the minimal cost under the given constraints.

Data preparation

The code first transforms the list of flights into a nested dictionary where the outer key is the departure city and the inner key is the arrival city. The inner value stores the price of that direct flight.

all = defaultdict(dict)
for f in flights:
    all[f[0]][f[1]] = f[2]

Using a defaultdict(dict) eliminates the need for explicit existence checks when later iterating over outgoing edges. If multiple flights exist between the same pair of cities, the last one in the input overwrites earlier entries, ensuring a single price per edge for the subsequent search.

State tracking

A dictionary named seen records the smallest number of stops with which a city has been reached so far. The comment clarifies that a city will only be revisited if a route arrives with fewer stops, which prevents unnecessary expansions.

seen = {}  # only visit a city again if we need less stops to get there

Priority queue initialization

The search starts with a heap containing a single tuple representing the source city: zero total cost, zero stops, and the source identifier.

schedule = [(0, 0, src)]  # heap (total price, stops, city)

The tuple ordering aligns with the heap’s default comparison, so the entry with the smallest total price is always popped first.

Main exploration loop

The core of the algorithm repeatedly extracts the cheapest pending route from the heap.

while schedule:
    total, stops, city = heappop(schedule)

    if city == dst:
        return total

    seen[city] = stops

    for next in all[city]:
        if stops <= k and (next not in seen or seen[next] > stops):
            price = all[city][next]
            heappush(schedule, (total + price, stops + 1, next))
  • The early-exit condition if city == dst: returns the accumulated cost as soon as the destination is the top of the heap, guaranteeing optimality because no cheaper route can remain in the queue.
  • After popping a city, the algorithm records the number of stops used to reach it in seen. This entry acts as a pruning key for future expansions.
  • The inner for loop iterates over all direct flights leaving the current city. The guard stops <= k ensures that a new leg is only considered when the stop count does not exceed the allowed limit. The additional check (next not in seen or seen[next] > stops) permits revisiting a city only if the new path uses fewer stops than any previously recorded path, which reduces redundant work.
  • When a neighbor qualifies, the new total price and incremented stop count are pushed onto the heap, preserving the best-first ordering.

Edge-case handling

  • Source equals destination - The initial heap entry contains the source city. If src and dst are identical, the first pop satisfies city == dst, and the function returns 0, correctly representing a zero-cost journey.
  • Zero-stop constraint (k == 0) - The guard stops <= k prevents any expansion beyond the source city, so only direct flights from src to dst are considered. If none exist, the loop exhausts the heap and the function returns -1.
  • Unreachable destination - When no sequence of flights satisfies the stop limit, the heap eventually empties, and the final return -1 signals impossibility.
  • Empty flight list - The adjacency map remains empty, causing the inner loop to have no iterations. The algorithm quickly terminates with -1 unless src equals dst.
  • Duplicate edges - By overwriting entries in the adjacency map, the code implicitly keeps the last supplied price for a given city pair. This deterministic handling avoids ambiguity during expansion.

Performance optimizations

  • Best-first ordering with a heap - By always expanding the cheapest partial route, the algorithm avoids exploring expensive paths that could never become optimal, reducing the number of heap operations.
  • Stop-based pruning via seen - Recording the minimal stop count for each city prevents revisiting a city with an equal or larger number of stops, cutting down the search space dramatically, especially in dense graphs.
  • Early termination on destination - Returning immediately when the destination is dequeued eliminates the need to process remaining heap entries, which can be substantial when many alternative routes exist.
  • Adjacency map using defaultdict - Direct access to outgoing edges without conditional checks speeds up neighbor enumeration. The nested dictionary structure also provides O(1) price lookup for each edge.
written by openai gpt

ELI5 - Simplified Explanation

Imagine a travel agency that wants to help a paper airplane reach a destination city. The computer looks at a big map showing every flight path and how much each trip costs. It starts by packing a little suitcase with the total money spent so far, how many stops have been made, and which city the plane is currently visiting.

The computer keeps a list of all these travel options and always chooses the cheapest one to try next. When the airplane lands in a new city, the computer remembers how many stops it took to get there. If the plane reaches the final city, the trip is finished. If it has not arrived yet, the computer looks at all the paths from the current city to the next ones. It only adds a new trip to the list if the plane has not used up all the allowed stops and if this new path is a smart way to travel compared to what has been seen before. This keeps happening until the airplane finds the very best way to reach the target city without taking too many detours.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.89 | σ = 1.73

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Java C++ Python TS
WalkCCC Java C++ Python
leetcode.ca Java C++ Python Go
LeetcodeHelp Java C++ Python
Progiez Java C++ Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fengvyi C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
martianoff Scala
qiyuangong Java
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak Python
yuanliu666 Kotlin
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fengvyi C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
martianoff Scala
qiyuangong Java
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak Python
yuanliu666 Kotlin
34 links | 22 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 easy 2 medium
5 solutions   October 6, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality