KatInterview

Fastest Delivery Route with Fuel Station Stops

Trees & GraphsAuto-graded · 17 test cases
HardAuto-gradedTrees & Graphsgraphsdijkstrashortest path

Last updated

Tests the ability to extend Dijkstra's algorithm with a constrained resource (fuel), requiring candidates to track both position and remaining fuel as state.

Fastest Delivery Route with Fuel Station Stops

You are building a routing engine for a delivery fleet. The city is modeled as a directed, weighted graph of n intersections (numbered 0 to n-1) connected by roads. Each road has a travel time (positive integer).

Your vehicle starts at intersection 0 with a full tank holding exactly k units of fuel. Every road segment consumes 1 unit of fuel regardless of its travel time. Certain intersections are fuel stations — arriving at one instantly refills your tank to k.

Find the minimum total travel time to reach intersection n-1 from intersection 0. If it is impossible to reach the destination, return -1.

Details

  • You begin at node 0 with k fuel. Node 0 itself is not a fuel station (unless listed as one).
  • Arriving at a fuel station (including potentially node n-1 if it appears in stations) refills to k immediately.
  • You may visit the same node more than once (e.g., to refuel), but the optimal solution never needs more than n * (k+1) state expansions.
  • If n == 1, you are already at the destination; return 0.

Input

ParameterTypeDescription
nintNumber of intersections (1 ≤ n ≤ 300)
roadsList[List[int]]Each element is [u, v, t] — a directed road from u to v with travel time t (1 ≤ t ≤ 1000)
stationsList[int]Intersections that are fuel stations (may be empty)
kintFull tank capacity (1 ≤ k ≤ 50)

Constraints

  • 1 ≤ n ≤ 300
  • 0 ≤ len(roads) ≤ 5000
  • 0 ≤ len(stations) ≤ n
  • 1 ≤ k ≤ 50
  • Road travel times are positive integers (1 ≤ t ≤ 1000)
  • There are no self-loops, but there may be multiple edges between the same pair of nodes.
  • Stations list may contain duplicates; treat them as a set.
  • Node indices in roads and stations are in range [0, n-1].

Examples

Example 1

Input: fastest_delivery(4, [[0, 1, 2], [1, 2, 3], [2, 3, 5], [0, 2, 10], [1, 3, 20]], [2], 2)

Output: 10

Example 2

Input: fastest_delivery(3, [[0, 1, 1], [1, 2, 1]], [], 1)

Output: -1

Example 3

Input: fastest_delivery(1, [], [], 3)

Output: 0

Hints

Hint 1

The key insight is that the state must include both the current node AND the remaining fuel — two different arrivals at the same node with different fuel levels are distinct states for Dijkstra.

Hint 2

Use a min-heap on (travel_time, node, fuel_remaining). When you arrive at a fuel station, set fuel to k before exploring neighbors.

Hint 3

To avoid revisiting a state (node, fuel) with higher cost, maintain a 2D dist array: dist[node][fuel] = best known travel time to reach that node with that much fuel remaining.