Staff Alert Relay

Mediumshortest pathAlso known as Network Delay Time

A hospital has no group chat for urgent notices. Instead it uses a relay: when a person gets an alert, they pass it on to a fixed list of colleagues. Each hand-off takes a known number of minutes. The nurse might phone the porter in 2 minutes, while the porter takes 9 minutes to walk over to the lab. Hand-offs only go one way: the porter passing to the lab does not mean the lab passes back.

Everyone forwards the alert the moment it first reaches them, to everyone on their list at once. The safety officer wants to know how long it takes, from the moment one person gets it, until the very last person has it.

Your task

Write alertTime(n, handoffs, start). Staff are numbered 0 to n - 1. Each entry [from, to, minutes] in handoffs means that once from has the alert, to receives it from them minutes later. The alert begins with start at minute 0.

Return the minute at which the last person receives the alert. Each person counts from the earliest moment any hand-off reaches them. Return -1 if some person never receives it.

alertTime(n: int, handoffs: int[][], start: int) → int

Examples

Example 1
Input
n = 4
handoffs = [[0, 1, 2], [0, 2, 9], [1, 2, 3], [2, 3, 1]]
start = 0
Output
6
Why

Person 1 has it at minute 2. Person 2 could get it straight from 0 at minute 9, but via 1 it arrives at 2 + 3 = 5. Person 3 gets it at 5 + 1 = 6. The last person is 3, at minute 6.

Example 2
Input
n = 3
handoffs = [[0, 1, 4], [2, 1, 1]]
start = 0
Output
-1
Why

Person 1 gets it at minute 4, but nobody passes anything to person 2. Hand-offs only go one way, so [2, 1, 1] does not help. Return -1.

Constraints

  • 1 ≤ n ≤ 1,000
  • 0 ≤ handoffs.length ≤ 5,000
  • 0 ≤ from, to < n and from ≠ to
  • 0 ≤ minutes ≤ 100
  • 0 ≤ start < n
  • The same pair may appear more than once with different times
Start with brute force

Breadth-first search counts hops, not minutes, so it gives wrong answers here. A correct slow approach repeats this n - 1 times: go through every hand-off and see if it gives its target an earlier time. That is Bellman-Ford.

With 1,000 people and 5,000 hand-offs, that is about 5 million checks, and it ignores the useful fact that no hand-off takes negative time. Dijkstra uses that fact to settle each person once, for about 5,000 × log 5,000 ≈ 60,000 heap steps.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code