Skip to content
Decoder

Network Delay Time

Medium

Problem

A network has n servers labelled 1 to n. Each entry [u, v, w] in times is a one-way link: a message sent from u reaches v after w milliseconds. You send a ping from server k. Return how long it takes until every server has received it, or -1 if some server never does.

Example 1

Input
times = [[2, 1, 1], [2, 3, 1], [3, 4, 1]], n = 4, k = 2
Output
2

Example 2

Input
times = [[1, 2, 1]], n = 2, k = 2
Output
-1
Why
links only go 1 → 2

Constraints

  • 1 <= n <= 100
  • 1 <= k <= n
  • 0 <= times.length <= 6000
  • 0 <= w <= 100
  • The same (u, v) pair may appear more than once; the faster link wins.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.