InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Advanced Graphs

Network Delay Time

medium Original ↗ 00:00

Problem

A network has n nodes labeled 1 to n. You’re given directed links times[i] = [u, v, w], meaning a signal sent from node u reaches node v after w units of time.

A signal is broadcast from node k. It propagates along every outgoing link simultaneously, and each node relays it onward the moment it arrives. Return the time at which the last node receives the signal — or -1 if some node never receives it.

Equivalently: compute the shortest travel time from k to every node, then return the maximum of those times (or -1 if any node is unreachable).

Examples

  • times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 22 — nodes 1 and 3 hear it at t=1, node 4 at t=2.
  • times = [[1,2,1]], n = 2, k = 11 — the single link delivers at t=1.
  • times = [[1,2,1]], n = 2, k = 2-1 — node 1 has no incoming path from node 2.

Constraints

  • 1 <= n <= 100, 1 <= k <= n
  • 1 <= len(times) <= 6000
  • 1 <= w <= 100; all weights are positive, which is what makes Dijkstra applicable

Think about it first

Hint 1 The answer is a function of single-source shortest paths: once you know the fastest arrival time at every node, the broadcast finishes at the maximum of them.
Hint 2 Bellman-Ford — relax every edge, repeat up to n - 1 times — computes all shortest paths in O(n · E) with a dozen lines and no data structures. With these constraints that already passes.
Hint 3 All weights are positive, so Dijkstra applies: keep a min-heap of (time, node), pop the earliest unsettled node, and relax its outgoing edges. The first pop of each node fixes its true arrival time, in O(E log V).

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug