Ctrl K

Runner-Up Route Through Traffic Lights

Hard
A city has crossings intersections numbered from 1 to crossings. Two-way roads are listed in roads, where roads[i] = [u, v] links intersections u and v. Every road takes exactly ride minutes to drive. Every intersection can be reached from every other. Each intersection has a traffic light. All lights switch at the same moment every switch minutes: at time 0 they have just turned green, after switch minutes they turn red, after another switch minutes green again, and so on. You may enter an intersection at any time but may leave it only on green. Waiting on green is not allowed: if the light is green, you must drive on immediately. A driver starts at intersection 1 at time 0 and heads to intersection crossings. Roads and intersections may be reused any number of times. Return the second smallest arrival time: the smallest time that is **strictly greater** than the fastest one.
Example 1
crossings=3, roads=[[1, 2], [2, 3], [1, 3]], ride=4, switch=5 → 8

The fastest trip is 1 → 3 directly: 4 minutes. The next best is 1 → 2 → 3: we reach crossing 2 at minute 4 while the light is still green (it changes at minute 5), drive on and arrive at minute 8.

Example 2
crossings=2, roads=[[1, 2]], ride=2, switch=3 → 8

The fastest time is 2 minutes. The second best comes from 1 → 2 → 1 → 2: reach 2 at minute 2 (green), get back to 1 at minute 4, where the light is red until minute 6, wait, and arrive at 2 at minute 8.

Constraints
  • 2 ≤ crossings ≤ 10⁴
  • crossings − 1 ≤ len(roads) ≤ min(2·10⁴, crossings·(crossings − 1)/2)
  • 1 ≤ u, v ≤ crossings, u ≠ v
  • Any two intersections share at most one road
  • The graph is connected
  • 1 ≤ ride, switch ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBall Into the Hole HardRepaint Arrows to Reach the Exit HardThrough the Walls to the Far Corner HardRooms on a Timer HardRoads on the Fastest Routes Hard
loading Python…
Input
crossings=3, roads=[[1, 2], [2, 3], [1, 3]], ride=4, switch=5
Expected
8

Run checks the first 3 tests in your browser. Submit checks all 86 tests on the server, hidden ones included.