Staff Alert Relay

Mediumshortest pathAlso known as Network Delay Time

A hospital passes urgent alerts by relay: each person who gets one passes it to a fixed list of colleagues, and each hand-off takes a known number of minutes. Hand-offs go one way only, so if the porter passes alerts to the lab, the lab does not necessarily pass them back.

Everyone forwards the alert to everyone on their list at once, the moment it first reaches them. The safety officer wants to know how long it takes until the 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 the alert at minute 2. Person 2 could get it straight from person 0 at minute 9, but through person 1 it arrives at 2 + 3 = 5. Person 3 gets it at 5 + 1 = 6, so the last person to receive it is person 3, at minute 6.

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

Person 1 gets the alert at minute 4, but nobody passes anything to person 2. Hand-offs only go one way, so [2, 1, 1] does not help person 2. The answer is -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 is wrong here. A correct but slow approach is Bellman-Ford, which repeats n - 1 times a pass over every hand-off and checks whether it gives its target an earlier time.

With 1,000 people and 5,000 hand-offs, that is about 5 million checks, and it does not use the fact that no hand-off takes negative time. Dijkstra's algorithm uses that fact to settle each person once, in 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