Cheapest Flights Within K Stops
Given n cities and flights [from, to, price] Find the cheapest price from src to dst with at most k stops Return -1 if no such route exists Example: n=3, flights=[[0,1,100],[1,2,100],[0,2,500]], src=0, dst=2, k=1 => 200
Cheapest Flights Within K Stops is about turning repeated work into a reusable state instead of re-solving subproblems. Interviewers love it because it reveals your state-and-transition thinking and your edge-case discipline. Once you define the right state, the transitions usually write themselves.
Examples
You write
find_cheapest_price(n: int, flights: List[List[int]], src: int, dst: int, k: int)
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
- returns
- 700
Example 2
- Input
- n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
- returns
- 200
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsGraphs
I reach for it when
- The input is edges, prerequisites or connections.
- You need cycles, an ordering or connected groups.
Say this before you type. Say whether the edges are directed, and which of the three jobs you are doing.
All 32 Graphs problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.