MediumNo. 0787
Cheapest Flights Within K Stops — LeetCode 787 Python Solution
- Pattern
- Heap / Priority Queue
- Topics
- Depth-First Search, Breadth-First Search, Graph, Dynamic Programming, Shortest Path, Heap (Priority Queue)
- On a study list
- NeetCode 150
- Reading time
- 2 min
- Source
- leetcode.com
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
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
- Time
- O(n·m) (typical)
- Space · auxiliary
- O(n·m)or optimized
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
| No. | Problem | Difficulty |
|---|---|---|
| 0329 | Longest Increasing Path in a Matrix | Hard |
| 1786 | Number of Restricted Paths From First to Last Node | Medium |
| 2328 | Number of Increasing Paths in a Grid | Hard |
| 2858 | Minimum Edge Reversals So Every Node Is Reachable | Hard |
| 0514 | Freedom Trail | Hard |
| 0834 | Sum of Distances in Tree | Hard |
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.