Cheapest Flights Within K Stops — LeetCode 787 Python Solution

MediumDepth-First SearchBreadth-First SearchGraphDynamic ProgrammingShortest PathHeap (Priority Queue)
Problem
#787
Reading time
2 min

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.

Example

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
Explanation
The graph is shown above.

Python solution

Python
class Solution:
    def findCheapestPrice(
        self, n: int, flights: List[List[int]], src: int, dst: int, k: int
    ) -> int:
        INF = 0x3F3F3F3F
        dist = [INF] * n
        dist[src] = 0
        for _ in range(k + 1):
            backup = dist.copy()
            for f, t, p in flights:
                dist[t] = min(dist[t], backup[f] + p)
        return -1 if dist[dst] == INF else dist[dst]

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 787. Cheapest Flights Within K Stops is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

On a study list

This problem is on NeetCode 150.

Frequently asked questions

How hard is LeetCode 787. Cheapest Flights Within K Stops?
LeetCode 787. Cheapest Flights Within K Stops is rated Medium on LeetCode.
What topics does LeetCode 787. Cheapest Flights Within K Stops cover?
LeetCode 787. Cheapest Flights Within K Stops is tagged Depth-First Search, Breadth-First Search, Graph, Dynamic Programming, Shortest Path and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview