KatInterview

Minimum Cost Route with Limited Layovers

Trees & GraphsAuto-graded · 21 test cases
HardAuto-gradedTrees & Graphsgraphsshortest-pathbellman-ford

Last updated

Tests understanding of constrained shortest-path algorithms on directed weighted graphs with edge-count restrictions.

You have a network of cities connected by direct flights. Each flight has a fixed price. Your task is to find the lowest-cost route between two cities, subject to a limit on how many intermediate cities you can pass through.

Write a function that takes:

  • n: the total count of cities, numbered from 0 to n-1
  • flights: a list where each entry is [origin, destination, cost], representing a one-way flight
  • source: the city where your journey begins
  • target: the city where your journey ends
  • max_layovers: the maximum number of intermediate cities allowed on your route

A layover is a city you pass through between source and target. For example, the route A → B → C → D has two layovers (cities B and C), meaning it uses three flights.

Return the minimum total cost of any valid route from source to target. If no valid route exists, return -1.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ flights.length ≤ n * (n - 1)
  • flights[i].length == 3
  • 0 ≤ origin, destination < n
  • origin ≠ destination
  • 0 ≤ cost ≤ 10⁴
  • 0 ≤ source, target < n
  • 0 ≤ max_layovers < n
  • All flight costs are non-negative

Examples

Example 1

Input: min_cost_route(4, [[0, 1, 100], [1, 2, 100], [2, 3, 100], [0, 3, 500]], 0, 3, 1)

Output: 500

Hints

Hint 1

Think about how many flights you can take if you're allowed max_layovers intermediate stops.

Hint 2

A modified Bellman-Ford that runs for a limited number of iterations naturally enforces an edge-count constraint.

Hint 3

Make sure to snapshot the cost array before each relaxation round to avoid accidentally counting paths with more edges than intended.