Network Delay Time
Compute when all nodes receive a signal sent from one node through weighted directed edges.
Open on LeetCode ↗Intuition
Taking the fewest edges does not minimize travel time when weights differ. Each node receives the signal at its shortest-path distance from the source, which Dijkstra calculates for nonnegative weights. Processing the closest unsettled node makes its distance final. The network delay is the largest finalized distance, unless some node is unreachable.
Single-source minimum arrival times with nonnegative weighted edges point directly to Dijkstra's algorithm. A request for the time until everyone is reached asks for the maximum finite shortest-path distance.
Approach
Build directed weighted adjacency lists
For every triple (u, v, w), store (v, w) under u. Direction matters because a signal may travel from u to v without a reverse route.
Finalize arrival times with a min-heap
Start the heap at (0, k). Skip a popped node if it was already finalized; otherwise record its cost and push every outgoing neighbor with accumulated travel time.
Measure the last receiver
If exactly n nodes were finalized, the maximum recorded distance is when the last node receives the signal. If fewer were reached, return -1 to report disconnection.
Solution
Common pitfalls
Treating edges as undirected
graph[v].append((u, w))
graph[u].append((v, w))
The listed travel time applies only in the given direction.
Using edge count instead of weight
heappush(heap, (cost + 1, neighbor))
heappush(heap, (cost + weight, neighbor))
Arrival time accumulates the provided edge weights.
Returning a maximum for a disconnected graph
return max(distance.values())
return max(distance.values()) if len(distance) == n else -1
Missing nodes mean the signal never reaches the entire network.
Edge cases
Its distance is zero, so the delay is zero.
Both candidates may enter the heap, and the lower arrival is finalized first.
It never becomes finalized, so return -1.