#2045
Second Minimum Time to Reach Destination
HardBreadth-First SearchGraph TheoryShortest PathGraph TraversalDijkstra's AlgorithmPriority Queue
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(E log V) |
| Space | O(1) | O(V) |
💡
Intuition
Time O(E log V)Space O(V)
The optimal solution uses a modified Dijkstra's algorithm to efficiently find the second minimum time by considering the traffic signal changes. This approach allows us to explore paths while keeping track of the minimum and second minimum times without exhaustively searching all paths.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a priority queue to explore paths based on time.
- 2Step 2: For each vertex, track the minimum and second minimum time to reach it.
- 3Step 3: For each edge, calculate the time considering the traffic signal changes and update the priority queue.
solution.py29 lines
1# Full working Python code
2import heapq
3from collections import defaultdict
4
5def second_min_time(n, edges, time, change):
6 graph = defaultdict(list)
7 for u, v in edges:
8 graph[u].append(v)
9 graph[v].append(u)
10
11 min_time = [[float('inf'), float('inf')] for _ in range(n + 1)]
12 min_time[1][0] = 0
13 pq = [(0, 1)] # (current_time, node)
14
15 while pq:
16 current_time, node = heapq.heappop(pq)
17 for neighbor in graph[node]:
18 wait_time = (change - (current_time % change)) % change
19 leave_time = current_time + wait_time + time
20 if leave_time < min_time[neighbor][0]:
21 min_time[neighbor][1] = min_time[neighbor][0]
22 min_time[neighbor][0] = leave_time
23 heapq.heappush(pq, (leave_time, neighbor))
24 elif min_time[neighbor][0] < leave_time < min_time[neighbor][1]:
25 min_time[neighbor][1] = leave_time
26 heapq.heappush(pq, (leave_time, neighbor))
27
28 return min_time[n][1] if min_time[n][1] != float('inf') else -1
29ℹ
Complexity note: The time complexity is O(E log V) due to the priority queue operations, where E is the number of edges and V is the number of vertices. The space complexity is O(V) for storing the minimum times for each vertex.
- 1Understanding traffic signal timing is crucial for calculating wait times.
- 2Using a priority queue can significantly optimize the pathfinding process.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.