KatInterview

Fastest Signal Arrival Times Across a Relay Grid

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsdijkstrashortest-pathgraph

Last 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 origin itself is always 0.
  • If station i cannot be reached from origin by 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 0 is allowed.
  • The output must be a list of exactly n integers, indexed by station number.

Constraints

  • 1 <= n <= 10^4
  • 0 <= len(cables) <= 5 * 10^4
  • Each cable is [a, b, delay] with 0 <= a, b < n and 0 <= 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.