787. Cheapest Flights Within K Stops
At a Glance
- Topic: graphs
- Pattern: Bellman-Ford / layered relaxation (shortest-path family)
- Difficulty: Medium
- Companies: Amazon, Google, Microsoft, Meta, Bloomberg
- Frequency: High
- LeetCode: 787
Problem (one-liner)
Directed weighted flights among n cities. Find the cheapest price from src to dst when you may use at most k stops (each stop is an intermediate city; the usual Bellman–Ford layer trick relaxes for k+1 edge layers).
Core Basics
- Opening move: classify the object (interval, multiset, trie node, bitmask, overlapping sub-intervals…) and whether the answer lives in an enumeration, ordering, partition, graph walk, DP table, etc.
- Contracts: spell what a valid partial solution looks like at each step—the thing you inductively preserve.
- Complexity anchors: state the brute upper bound and the structural fact (sorting, monotonicity, optimal substructure, greedy exchange, hashability) that should beat it.
Understanding
- Why brute hurts: name the repeated work or state explosion in one sentence.
- Why optimal is safe: the invariant / exchange argument / optimal-subproblem story you would tell a staff engineer.
Memory Hooks
- One chant / rule: a single memorable handle (acronym, operator trick, or shape) you can recall under time pressure.
Recognition Cues
- Edge constraints on number of edges used — Bellman-Ford limited rounds
- Negative weights absent — BF rounds sufficient
Study Pattern (SDE3+)
- 0–3 min: restate I/O and brittle edges aloud, then verbalize two approaches with time/space before you touch the keyboard.
- Implementation pass: one-line invariant above the tight loop; state what progress you make each iteration.
- 5 min extension: pick one constraint twist (immutable input, stream, bounded memory, parallel readers) and explain what in your solution breaks without a refactor.
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Approaches
- State BFS
(city, stops)— okay memory. - Optimal — copy DP array each round like BF
k+1iterations —O(E·k)time.
Optimal Solution
Go
func findCheapestPrice(nodeCount int, flights [][]int, source int, destination int, maxStops int) int {
const infinity = 1 << 30
prices := make([]int, nodeCount)
for index := range prices {
prices[index] = infinity
}
prices[source] = 0
for round := 0; round <= maxStops; round++ {
nextPrices := append([]int(nil), prices...)
for _, flight := range flights {
from := flight[0]
to := flight[1]
cost := flight[2]
if prices[from] == infinity {
continue
}
candidate := prices[from] + cost
if candidate < nextPrices[to] {
nextPrices[to] = candidate
}
}
prices = nextPrices
}
if prices[destination] >= infinity {
return -1
}
return prices[destination]
}JavaScript
function findCheapestPrice(nodeCount, flights, source, destination, maxStops) {
const infinity = Number.POSITIVE_INFINITY;
let prices = new Array(nodeCount).fill(infinity);
prices[source] = 0;
for (let round = 0; round <= maxStops; round += 1) {
const nextPrices = [...prices];
for (const flight of flights) {
const [from, to, cost] = flight;
if (prices[from] === infinity) {
continue;
}
const candidate = prices[from] + cost;
if (candidate < nextPrices[to]) {
nextPrices[to] = candidate;
}
}
prices = nextPrices;
}
return prices[destination] === infinity ? -1 : prices[destination];
}Walkthrough
Round r represents routes using up to r edges from prior layer cost snapshot — prevents using same edge layer trick incorrectly by scanning fresh nextPrices each round.
Invariant: After maxStops+1 rounds, best price using ≤ maxStops intermediate vertices is captured.
Edge Cases
- No route —
-1 - Direct flight beats multi-hop
Pitfalls
- Mixing Bellman rounds without copying prior layer — allows extra hops within same round
Similar Problems
- 743. Network Delay Time — unconstrained hops Dijkstra
- 1976. Number of Ways to Arrive at Destination — shortest path counts
Variants
- Exactly
kstops — adjust rounds equality
Mind-Map Tags
#bellman-ford #layered-relaxation #flights #shortest-path
Mark this page when you finish learning it.
Last updated on
Spotted something unclear or wrong on this page?