TRT
Sign in
mediumAdvancedLeetCode#Bellman-Ford rounds#hop limit

Cheapest flights within K stops

Find the cheapest route with at most k stops by running k + 1 Bellman-Ford rounds over a copy of the previous round.

The Runtime Theory Team1 min read
Taught inNegative edges and Bellman-FordPro — members onlyWhen some weights are negative, Dijkstra's settled distances can be wrong. Bellman-Ford relaxes every edge V − 1 times instead, handles negative weights, and detects negative cycles, at a cost of O(V × E).
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inn = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1

out700

inn = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1

out200

inn = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0

out500

Return the cheapest price from src to dst using at most k stops (k + 1 flights), or -1.

Before you code

Plain Dijkstra keeps only the cheapest price per city and forgets how many flights were used, so it can discard a pricier route with fewer stops that was needed. Bellman-Ford's rounds count edges.

Hints

  1. Run k + 1 rounds. In each, start from a copy of the previous prices.
  2. For every flight (u, v, w), update new[v] = min(new[v], prev[u] + w).
  3. Reading only prev ensures each round adds at most one flight.

Production & complexity notes

When solving Cheapest flights within K stops on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Negative edges and Bellman-Ford to reinforce the underlying pattern.

What it practices

Bellman-Ford rounds as a hop limit, from Negative edges and Bellman-Ford.

Not started

Sign in to save your learning progress.

Sign in to save