Second Minimum Time to Reach Destination - Problem
๐ฆ Navigate Through Traffic Lights to Find the Second Fastest Route
Imagine you're navigating through a city where every intersection has traffic lights that change color simultaneously every few minutes. You need to find the second minimum time to travel from intersection 1 to intersection n.
The city is represented as a bi-directional graph where:
- Each vertex (1 to n) represents an intersection
- Each edge represents a road that takes exactly
timeminutes to traverse - Every intersection has a traffic signal that alternates between green and red every
changeminutes - All signals start green and change simultaneously
Traffic Rules:
- ๐ข You can enter an intersection at any time
- ๐ข You can only leave an intersection when the light is green
- ๐ด If you arrive at an intersection when the light is red, you must wait
- โ ๏ธ You cannot wait at an intersection if the light is green (you must leave immediately)
Your goal is to find the second minimum time to reach destination n from source 1. The second minimum is defined as the smallest time that is strictly larger than the minimum time.
Input & Output
example_1.py โ Basic Graph
$
Input:
n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5
โบ
Output:
13
๐ก Note:
The shortest path is 1โ4โ5 taking 9 minutes. The second shortest path is 1โ3โ4โ5 taking 13 minutes (with potential traffic light delays).
example_2.py โ Simple Path
$
Input:
n = 2, edges = [[1,2]], time = 3, change = 2
โบ
Output:
11
๐ก Note:
Only one direct path 1โ2. The shortest time is 3 minutes. To get the second shortest, we must wait for a red light cycle, giving us 3 + 2 + 3 + 3 = 11 minutes.
example_3.py โ Multiple Paths
$
Input:
n = 4, edges = [[1,2],[2,3],[1,3],[3,4]], time = 2, change = 4
โบ
Output:
8
๐ก Note:
Shortest path 1โ3โ4 takes 4 minutes. Second shortest 1โ2โ3โ4 takes 6 minutes. With traffic lights, the second shortest becomes 8 minutes.
Constraints
- 2 โค n โค 104
- n - 1 โค edges.length โค min(2 ร 104, n ร (n - 1) / 2)
- edges[i].length == 2
- 1 โค ui, vi โค n
- ui != vi
- No duplicate edges and graph is connected
- 1 โค time, change โค 103
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Journey
Start at intersection 1 with all traffic lights green, ready to explore optimal routes
2
Calculate Timing
At each intersection, check if traffic light is green (go) or red (wait for next cycle)
3
Track Best Routes
Maintain the fastest and second-fastest arrival time to each intersection
4
BFS Exploration
Use breadth-first search to systematically explore all possible paths
5
Find Second Best
Return the second minimum time to reach the destination
Key Takeaway
๐ฏ Key Insight: Use modified BFS to efficiently find the second minimum path while properly handling traffic light constraints by tracking two arrival times per vertex.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code