Data Structures & Algorithms Advanced Graphs
💡
Exercise 120

Cheapest Flights K Stops 30 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Find the cheapest flight from src to dst with at most K stops. Modified Dijkstra or BFS with level constraint. Bellman-Ford with K+1 iterations also works.

Bellman-Ford: relax all edges K+1 times. Each iteration allows one more stop. Use a copy of prices to avoid using updates from the same iteration.

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Find cheapest price from src to dst with at most k stops.
Bellman-Ford: iterate k+1 times. Each iteration, for each flight, if src reachable, try to relax dst. Use temp copy.
🧪 Test Cases
Input
findCheapestPrice(3, flights, 0, 2, 1)
Expected
200
Test case 1
Input
findCheapestPrice(3, flights, 0, 2, 0)
Expected
500
Test case 2
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.