CodeArchon

mediumAdvanced GraphsAmazonFacebook

Budget Flight Finder

A budget traveler finds the cheapest ticket chain from src to dst using at most k layovers.

Given n cities, directed flights with prices, src, dst, and k, return the cheapest price with at most k stops. -1 if no such route.

Choose approach

0
1
2
1/4
Narrationstep 1 of 4

Bellman-Ford limited to 2 rounds (≤ 1 stops).

1def findCheapestPrice(n, flights, src, dst, k):
2 dist = [float('inf')] * n; dist[src] = 0
3 for _ in range(k + 1):
4 nxt = dist[:]
5 for u, v, w in flights:
6 if dist[u] + w < nxt[v]: nxt[v] = dist[u] + w
7 dist = nxt
8 return -1 if dist[dst] == float('inf') else dist[dst]
Variables
src=0
dst=2
k=1

How to think about it

  1. 'At most k stops' = at most k+1 edges = k+1 Bellman-Ford rounds.
  2. Cloning prevents a single round from using more than one new edge.
  3. Dijkstra variants exist but require augmented state (city, stops_used).

Edge cases to catch in interview

  • Direct flight within k stops -> that price.
  • No reachable route under k stops -> -1.

Examples

Example 1500
{"n":3,"flights":[[0,1,100],[1,2,100],[0,2,500]],"src":0,"dst":2,"k":0}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed