Leetcode #2045: Second Minimum Time to Reach Destination
In this guide, we solve Leetcode #2045 Second Minimum Time to Reach Destination 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
A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Breadth-First Search, Graph, Shortest Path
Intuition
The data forms a graph, so we should explore nodes and edges systematically.
A traversal ensures we visit each node once while maintaining the needed state.
Approach
Build an adjacency list and traverse with BFS or DFS.
Aggregate results as you visit nodes.
Steps:
- Build the graph.
- Traverse with BFS/DFS.
- Accumulate the required output.
Example
Input: n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5
Output: 13
Explanation:
The figure on the left shows the given graph.
The blue path in the figure on the right is the minimum time path.
The time taken is:
- Start at 1, time elapsed=0
- 1 -> 4: 3 minutes, time elapsed=3
- 4 -> 5: 3 minutes, time elapsed=6
Hence the minimum time needed is 6 minutes.
The red path shows the path to get the second minimum time.
- Start at 1, time elapsed=0
- 1 -> 3: 3 minutes, time elapsed=3
- 3 -> 4: 3 minutes, time elapsed=6
- Wait at 4 for 4 minutes, time elapsed=10
- 4 -> 5: 3 minutes, time elapsed=13
Hence the second minimum time is 13 minutes.
Python Solution
class Solution:
def secondMinimum(
self, n: int, edges: List[List[int]], time: int, change: int
) -> int:
g = defaultdict(set)
for u, v in edges:
g[u].add(v)
g[v].add(u)
q = deque([(1, 0)])
dist = [[inf] * 2 for _ in range(n + 1)]
dist[1][1] = 0
while q:
u, d = q.popleft()
for v in g[u]:
if d + 1 < dist[v][0]:
dist[v][0] = d + 1
q.append((v, d + 1))
elif dist[v][0] < d + 1 < dist[v][1]:
dist[v][1] = d + 1
if v == n:
break
q.append((v, d + 1))
ans = 0
for i in range(dist[n][1]):
ans += time
if i < dist[n][1] - 1 and (ans // change) % 2 == 1:
ans = (ans + change) // change * change
return ans
Complexity
The time complexity is O(V+E). The space complexity is O(V).
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.