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.
Example 1:
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.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.
Example 2:
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
Example 3:
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
Constraints:
2 <= n <= 100
0 <= flights.length <= (n * (n - 1) / 2)
flights[i].length == 3
0 <= fromi, toi < n
fromi != toi
1 <= pricei <= 104
There will not be any multiple flights between two cities.
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Minimum Cost to Reach City With Discounts (minimum-cost-to-reach-city-with-discounts)
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #787: Cheapest Flights Within K Stops
class Solution {
private static final int INF = 0x3f3f3f3f;
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
int[] dist = new int[n];
int[] backup = new int[n];
Arrays.fill(dist, INF);
dist[src] = 0;
for (int i = 0; i < k + 1; ++i) {
System.arraycopy(dist, 0, backup, 0, n);
for (int[] e : flights) {
int f = e[0], t = e[1], p = e[2];
dist[t] = Math.min(dist[t], backup[f] + p);
}
}
return dist[dst] == INF ? -1 : dist[dst];
}
}
// Accepted solution for LeetCode #787: Cheapest Flights Within K Stops
func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int {
const inf = 0x3f3f3f3f
dist := make([]int, n)
backup := make([]int, n)
for i := range dist {
dist[i] = inf
}
dist[src] = 0
for i := 0; i < k+1; i++ {
copy(backup, dist)
for _, e := range flights {
f, t, p := e[0], e[1], e[2]
dist[t] = min(dist[t], backup[f]+p)
}
}
if dist[dst] == inf {
return -1
}
return dist[dst]
}
# Accepted solution for LeetCode #787: Cheapest Flights Within K Stops
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]
// Accepted solution for LeetCode #787: Cheapest Flights Within K Stops
struct Solution;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::i32;
#[derive(Eq, Debug)]
struct State {
position: usize,
stop: usize,
cost: i32,
}
impl Ord for State {
fn cmp(&self, other: &Self) -> Ordering {
other.cost.cmp(&self.cost)
}
}
impl PartialOrd for State {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for State {
fn eq(&self, other: &Self) -> bool {
self.cost == other.cost
}
}
#[derive(Copy, Clone)]
struct Edge {
u: usize,
v: usize,
cost: i32,
}
impl Solution {
fn find_cheapest_price(n: i32, flights: Vec<Vec<i32>>, src: i32, dst: i32, k: i32) -> i32 {
let n = n as usize;
let src = src as usize;
let dst = dst as usize;
let k = k as usize;
let mut prices = vec![i32::MAX; n];
prices[src] = 0;
let mut edges: Vec<Vec<Edge>> = vec![vec![]; n];
for f in flights {
let u = f[0] as usize;
let v = f[1] as usize;
let cost = f[2];
edges[u].push(Edge { u, v, cost });
}
let mut pq: BinaryHeap<State> = BinaryHeap::new();
pq.push(State {
position: src,
stop: 0,
cost: 0,
});
while let Some(s) = pq.pop() {
if s.position == dst {
return s.cost;
}
prices[s.position] = i32::min(s.cost, prices[s.position]);
if s.stop <= k {
for e in &edges[s.position] {
pq.push(State {
position: e.v,
cost: s.cost + e.cost,
stop: s.stop + 1,
});
}
}
}
if prices[dst] == i32::MAX {
-1
} else {
prices[dst]
}
}
}
#[test]
fn test() {
let n = 3;
let flights = vec![vec![0, 1, 100], vec![1, 2, 100], vec![0, 2, 500]];
let src = 0;
let dst = 2;
let k = 1;
assert_eq!(Solution::find_cheapest_price(n, flights, src, dst, k), 200);
}
// Accepted solution for LeetCode #787: Cheapest Flights Within K Stops
function findCheapestPrice(
n: number,
flights: number[][],
src: number,
dst: number,
k: number,
): number {
const adjacencyList = new Map();
for (let [start, end, cost] of flights) {
if (adjacencyList.has(start)) {
adjacencyList.get(start).push([end, cost]);
} else {
adjacencyList.set(start, [[end, cost]]);
}
}
const queue = [[0, src, k + 1]];
const visited = new Map();
while (queue.length) {
queue.sort((a, b) => a[0] - b[0]);
const [cost, city, stops] = queue.shift();
visited.set(city, stops);
if (city === dst) {
return cost;
}
if (stops <= 0 || !adjacencyList.has(city)) {
continue;
}
for (let [nextCity, nextCost] of adjacencyList.get(city)) {
if (visited.has(nextCity) && visited.get(nextCity) >= stops - 1) {
continue;
}
queue.push([cost + nextCost, nextCity, stops - 1]);
}
}
return -1;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.