Network Delay Time

Medium Advanced graphs

The nodes of a network are numbered from 1 to n. Each entry [u, v, w] of times is a one-way link: a signal at node u gets to node v w units of time later.

A signal starts from node k at time 0 and goes out along every link of every node it reaches, all at once, so each node hears it as soon as the quickest way there allows.

Return the time at which the last node hears the signal, or -1 if some node never hears it.

Example 1

Input: times = [[1,2,9],[1,3,2],[3,4,2],[4,2,3],[2,5,1]], n = 5, k = 1
Output: 8

The signal reaches 3 at time 2 and 4 at time 4. The link straight to 2 takes 9, but through 3 and 4 the signal arrives at 7, so 5, one more link on, hears it at 8, last of all.

Example 2

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

Example 3

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

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ k ≤ n
  • 0 ≤ times.length ≤ 10⁵
  • times[i] = [u, v, w], with 1 ≤ u, v ≤ n, u ≠ v and 0 ≤ w ≤ 10⁴
  • No two links go from the same node to the same node

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

More Advanced graphs

All Advanced graphs problems