Skip to content
Decoder

Cheapest Flights Within K Stops

Medium

Problem

There are n cities and a list of one-way flights, where [from, to, price] is a flight costing price. Return the cheapest price to get from src to dst using at most `k` stops (a stop is a city you land in between src and dst, so at most k + 1 flights). Return -1 if no such route exists.

Example 1

n = 4, flights = [[0, 1, 100], [1, 2, 100], [2, 0, 100], [1, 3, 600], [2, 3, 200]]

Example 2

Input
src = 0, dst = 3, k = 1
Output
700
Why
0 → 1 → 3; the cheaper 0 → 1 → 2 → 3 needs 2 stops

Example 3

n = 3, flights = [[0, 1, 100], [1, 2, 100], [0, 2, 500]]

Example 4

Input
src = 0, dst = 2, k = 0
Output
500
Why
no stops allowed, so fly direct

Constraints

  • 1 <= n <= 100
  • 0 <= flights.length <= n * (n - 1) / 2
  • 1 <= price <= 10^4
  • 0 <= src, dst, k < n and src != dst

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.