Leetcode #1928: Minimum Cost to Reach Destination in Time
In this guide, we solve Leetcode #1928 Minimum Cost to Reach Destination in Time in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Graph, Array, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
Output: 11
Explanation: The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.
Python Solution
class Solution:
def minCost(
self, maxTime: int, edges: List[List[int]], passingFees: List[int]
) -> int:
m, n = maxTime, len(passingFees)
f = [[inf] * n for _ in range(m + 1)]
f[0][0] = passingFees[0]
for i in range(1, m + 1):
for x, y, t in edges:
if t <= i:
f[i][x] = min(f[i][x], f[i - t][y] + passingFees[x])
f[i][y] = min(f[i][y], f[i - t][x] + passingFees[y])
ans = min(f[i][n - 1] for i in range(m + 1))
return ans if ans < inf else -1
Complexity
The time complexity is , where and are the number of edges and cities, respectively. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.