Python coding

Signal arrival time

A signal starts at server source in a network of n servers labelled 1 to n. Each entry of links is [u, v, ms]: a one-way link that carries the signal from u to v in ms milliseconds. A server forwards the signal on all its outgoing links as soon as it first receives it. Return how many milliseconds pass until every server has the signal, or -1 if some server never gets it.

Latencies are non-negative integers; the same link may appear twice.

Besides the tests, one large input (1,000 servers, 10,000 links) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • arrival_time(4, [[2,1,1],[2,3,1],[3,4,1]], 2) → 2
  • arrival_time(3, [[1,2,10],[1,3,1],[3,2,2]], 1) → 3
  • arrival_time(2, [[1,2,1]], 2) → -1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Each server's arrival time is its shortest-path distance from source. The weights are non-negative, so Dijkstra applies.

Hint 2

Pop the closest server from a min-heap, skip stale entries and relax its links. At the end, check that all n servers were reached, then take the maximum.

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

def arrival_time(n: int, links: list[list[int]], source: int) -> int:
    adj = {}
    for u, v, w in links:
        adj.setdefault(u, []).append((v, w))
    dist = {source: 0}
    heap = [(0, source)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue                     # stale entry: heapq has no decrease-key
        for v, w in adj.get(u, []):
            if d + w < dist.get(v, float("inf")):
                dist[v] = d + w          # relax
                heapq.heappush(heap, (d + w, v))
    return max(dist.values()) if len(dist) == n else -1

Arrival time is shortest-path distance, and with non-negative latencies the first time Dijkstra pops a server its distance is final. The answer is the slowest server, and only if all n were reached. Traps: BFS counts hops, not milliseconds (1→3→2 at 3 ms beats the direct 10 ms link); marking servers done when pushed instead of popped locks in that 10; skipping the stale check d > dist[u] re-expands old heap entries.