Network Delay Time

35 min · networkDelayTime()

One server sends an alert. How long until the slowest machine in the network hears it?

You receive n nodes numbered from 1 through n and a list times. Each entry [u, v, w] describes a directed edge — a one-way connection from u to v that takes w units of time to cross. A signal starts at node k at time 0.

Return the first time by which every node has received the signal. The signal follows the fastest available route to each node, so your answer is the largest of those fastest arrival times. Return -1 when even one node can't be reached from k.

A connection may point from a node back to itself. No directed pair appears more than once, and every travel time is positive.

Constraints

  • 1 <= n <= 100
  • 1 <= times.length <= 6_000
  • Every times[i] is [u, v, w] with 1 <= u, v <= n and 1 <= w <= 100.
  • Directed pairs (u, v) are distinct.
  • 1 <= k <= n

Hints

What does each arrival need?

You need the shortest travel time from one source, k, to every node. Once you have those distances, the answer is their maximum — unless one is still infinite.

Use the positive weights

Every edge costs at least 1. That makes Dijkstra's algorithm a fit: repeatedly finalize the unreached node with the smallest known arrival time.

Stale queue entries are harmless

When a shorter route is found, push the new distance. If an older, larger entry comes out later, compare it with the current best distance and skip it.

Follow-up

How would your choice change if some travel times could be negative, while negative cycles were still forbidden?

Visible cases

Examples

Example 1

ready
Input
times = [
  [
    2,
    1,
    1
  ],
  [
    2,
    3,
    1
  ],
  [
    3,
    4,
    1
  ]
]
n = 4
k = 2
Expected
2
Why
node 4 receives the signal last, at time 2

Example 2

ready
Input
times = [
  [
    1,
    2,
    5
  ]
]
n = 3
k = 1
Expected
-1
Why
node 3 has no route from the source

Example 3

ready
Input
times = [
  [
    1,
    1,
    100
  ]
]
n = 1
k = 1
Expected
0
Why
the only node has the signal at time 0

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite