Fastest Signal Arrival Times Across a Relay Grid
Trees & GraphsAuto-graded · 18 test casesLast updated
Compute shortest-path distances from one source in an undirected graph with non-negative weights, handling parallel edges, self-loops, and unreachable nodes.
Fastest Signal Arrival Times Across a Relay Grid
A company runs a network of n relay stations numbered 0 through n - 1. Stations are joined by two-way cables. Each cable is described by a triple [a, b, delay]: it connects station a and station b, and a signal takes delay milliseconds to cross it in either direction.
A signal is emitted from station origin. For every station i from 0 to n - 1, determine the smallest total time in which the signal can arrive at station i, where the total time is the sum of the delays of the cables used along the route.
Task
Implement a function that takes the number of stations, the list of cables, and the origin station, and returns a list of n integers. The value at index i is the minimum arrival time at station i.
Rules
- The value for
originitself is always0. - If station
icannot be reached fromoriginby any sequence of cables, its value is-1. - Several cables may join the same pair of stations, possibly with different delays. Any of them may be used, so effectively the cheapest one matters.
- A cable may connect a station to itself (
a == b). Such a cable never helps and must not change any result. - A delay of
0is allowed. - The output must be a list of exactly
nintegers, indexed by station number.
Constraints
1 <= n <= 10^40 <= len(cables) <= 5 * 10^4- Each cable is
[a, b, delay]with0 <= a, b < nand0 <= delay <= 10^9 0 <= origin < n
Examples
Example 1
Input: fastest_arrival_times(4, [[0, 1, 10], [0, 2, 30], [1, 2, 10], [1, 1, 5]], 0)
Output: [0, 10, 20, -1]
Example 2
Input: fastest_arrival_times(3, [[0, 1, 50], [0, 1, 20], [1, 2, 15]], 0)
Output: [0, 20, 35]
Hints
Hint 1
All delays are non-negative, so a greedy shortest-path method that always finalizes the closest unfinalized station works.
Hint 2
Build an adjacency list that stores each cable in both directions; keep parallel cables and self-loops as they are, since relaxation handles them naturally.
Hint 3
Use a min-heap of (time, station). When you pop an entry whose time is larger than the best known time for that station, skip it. At the end, replace any station that was never reached with -1.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a single-source shortest path problem on an undirected graph with non-negative edge weights, which is the classic use case for Dijkstra's algorithm.
- Build an adjacency list, adding each cable in both directions. Parallel cables and self-loops are stored unchanged.
- Set the best time of
originto0and all others to infinity. Push(0, origin)onto a min-heap. - Repeatedly pop the smallest
(time, station)entry. Iftimediffers from the recorded best time for that station, the entry is stale and is skipped. Otherwise, try each cable out of the station: iftime + delaybeats the neighbor's recorded best, update it and push the new entry. - When the heap is empty, convert any remaining infinity to
-1.
Why it is correct
When a station is popped with a non-stale time, that time is final. Suppose a shorter route existed. Follow it from the origin until it first leaves the set of finalized stations at some station y. The edge into y was already relaxed, so the heap holds an entry for y with time no greater than that route's prefix, which is at most the full route length because delays are non-negative. That is smaller than the popped time, so y would have been popped first, a contradiction.
Special cases follow naturally:
- Parallel cables: each is relaxed independently and only the cheapest can improve a neighbor.
- Self-loops: the candidate
best[x] + delayis never strictly less thanbest[x], so nothing changes. - Unreachable stations: never pushed, so they remain infinity and become
-1. - Zero delays: fine, since only non-negativity is needed.
Complexity
Let m = len(cables). Each successful relaxation pushes at most one heap entry, so there are at most 2m + 1 pushes.
- Time:
O((n + m) log m) - Space:
O(n + m)
Reference solution
import heapq
from typing import List
def fastest_arrival_times(n: int, cables: List[List[int]], origin: int) -> List[int]:
adj = [[] for _ in range(n)]
for a, b, delay in cables:
adj[a].append((b, delay))
adj[b].append((a, delay))
INF = float('inf')
best = [INF] * n
best[origin] = 0
heap = [(0, origin)]
while heap:
t, node = heapq.heappop(heap)
if t != best[node]:
continue
for nxt, delay in adj[node]:
cand = t + delay
if cand < best[nxt]:
best[nxt] = cand
heapq.heappush(heap, (cand, nxt))
return [-1 if t == INF else t for t in best]