InterviewPrepKit

Home / Coding / Advanced Graphs

Network Delay Time

medium Original ↗
Solving tips
  • This is single-source shortest paths, and the answer is the MAX over all node distances (last node to hear the signal), not one target.
  • Weights are positive, so reach for Dijkstra with a min-heap of (time, node); the first pop of each node fixes its final distance.
  • Use lazy deletion: skip a popped node already settled, avoiding decrease-key operations.
  • Return -1 if any node is unreachable (fewer than n settled or a leftover infinity); target O(E log V) time.

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 (this is what licenses Dijkstra)

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 — O(E log V).
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.