KatInterview

Minimum Travel Cost with Layover Limit

Trees & GraphsAuto-graded · 24 test cases
MediumAuto-gradedTrees & Graphsgraphsbellman-fordshortest-path

Last updated

Tests weighted shortest-path reasoning under a hard constraint on the number of edges traversed, requiring a round-bounded relaxation strategy.

Problem Statement

You are planning a trip across a network of cities connected by one-way routes. Each route has a fixed fare. Given the network, a starting city, a destination city, and a maximum number of layovers allowed, find the lowest total fare for any valid itinerary.

You are given:

  • num_cities — the total number of cities, labeled 0 through num_cities - 1.
  • routes — a list of connections, where each routes[i] = [origin, destination, fare] describes a direct one-way flight with the given fare.
  • start — the city you depart from.
  • end — the city you need to reach.
  • max_layovers — the maximum number of intermediate stops (layovers) permitted.

Return the minimum total fare to travel from start to end using at most max_layovers intermediate stops. If no valid itinerary exists, return -1.

A trip with max_layovers = 1 may use at most two flights: one from start to some intermediate city, and one onward to end. A direct flight uses zero layovers.

If start equals end, the cost is 0 regardless of the routes available.

Constraints

  • 1 <= num_cities <= 100
  • 0 <= len(routes) <= num_cities * (num_cities - 1) / 2
  • 0 <= origin, destination, start, end < num_cities
  • 0 <= fare <= 10,000
  • 0 <= max_layovers < num_cities
  • There are no negative fares.

Examples

Example 1

Input: min_travel_cost(4, [[0, 1, 100], [1, 2, 100], [2, 3, 200], [1, 3, 600]], 0, 3, 1)

Output: 700

Example 2

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

Output: 200

Example 3

Input: min_travel_cost(3, [[0, 1, 100], [1, 2, 100]], 0, 2, 0)

Output: -1

Example 4

Input: min_travel_cost(4, [[0, 1, 100], [1, 2, 100]], 0, 0, 0)

Output: 0

Hints

Hint 1

An itinerary with at most k layovers uses at most k + 1 individual flights — think in terms of the number of edges (flights) rather than the number of nodes (cities).

Hint 2

Consider processing all routes in rounds, where round i computes the cheapest way to reach each city using exactly i flights. Crucially, within a single round you should only use costs from the previous round, not ones updated during the current round — otherwise a single round could silently chain multiple flights.

Hint 3

If you snapshot the cost array at the start of each round and write updates into the copy, you prevent that chaining problem and stay within the edge budget. Run exactly k + 1 such rounds.