Python coding

Second fastest arrival

A city has n intersections numbered 0 to n - 1. Each entry of roads is [u, v, minutes]: a two-way road between u and v that takes minutes to drive. A route from 0 to n - 1 may pass through the same intersection or road more than once. Return the second best arrival time: the smallest route time that is strictly greater than the fastest one. Return -1 if n - 1 cannot be reached.

n ≥ 2; every road takes at least 1 minute, no road joins an intersection to itself, and two intersections may be joined by several roads.

Besides the tests, one large input (24 intersections in a ladder) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • second_fastest(4, [[0,1,2],[1,3,2],[0,2,3],[2,3,2]]) → 5
  • second_fastest(2, [[0,1,5]]) → 15
  • second_fastest(3, [[0,1,1]]) → -1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

The second best route to n - 1 arrives from some neighbor at that neighbor's best or second best time. So two times per intersection are enough.

Hint 2

Run Dijkstra with best and second arrays. A new time below best demotes the old best to second; a time strictly between them becomes second. Push every new time.

Hint 3

Skip a popped entry only when it is worse than that intersection's second: each intersection is expanded at most twice.

Solution and why it works
pythonO(n + E log E), E = len(roads) · O(n + E)
import heapq


def second_fastest(n: int, roads: list[list[int]]) -> int:
    adj = [[] for _ in range(n)]
    for u, v, w in roads:
        adj[u].append((v, w))
        adj[v].append((u, w))
    best, second = [float("inf")] * n, [float("inf")] * n
    best[0] = 0
    heap = [(0, 0)]
    while heap:
        t, u = heapq.heappop(heap)
        if t > second[u]:
            continue                             # u already has two better times
        for v, w in adj[u]:
            nt = t + w
            if nt < best[v]:
                best[v], second[v] = nt, best[v]  # the old best becomes the runner-up
                heapq.heappush(heap, (nt, v))
            elif best[v] < nt < second[v]:       # strictly between: ties don't count
                second[v] = nt
                heapq.heappush(heap, (nt, v))
    return -1 if second[n - 1] == float("inf") else second[n - 1]

Cut the second best route before its last road: the part before reaches that neighbor at its best or second best time; if it were slower, the neighbor's two best times would give two faster, distinct arrivals. So keeping two distinct times per intersection and relaxing from both is exact, and each intersection is expanded at most twice. Traps: a tie with the fastest is not second best, and a route may bounce back and forth on one road.