The Runtime Theory
mediumleetcode#weighted-graph#dijkstra#shortest-path

Network Delay Time

Model one-way network links as a weighted directed graph and find when every reachable node receives a signal.

The Runtime Theory Team1 min read
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

intimes=[[2,1,1],[2,3,1],[3,4,1]], n=4, k=2

out2

intimes=[[1,2,1]], n=2, k=2

out-1

intimes=[[1,2,4],[1,3,1],[3,2,1]], n=3, k=1

out2

Treat each directed link as an edge whose weight is the time for a signal to travel across it. Starting from node k, find the shortest travel time to every node. The answer is the largest of those shortest times: the last node's arrival time. If at least one node is unreachable, return -1.

For the first case, node 2 reaches node 1 in one unit and node 3 in one unit. Node 4 is reached through node 3 in two units, so the whole network receives the signal after 2 units.

A useful approach

Build an adjacency list and run Dijkstra's algorithm from k. Use a min-priority queue so the next node with the smallest known distance is processed first. When a shorter route to a neighbor is found, update its distance and add it to the queue. The maximum finite distance is the answer only if every node has one.

With a binary heap, the usual running time is O((V + E) log V) and the space use is O(V + E), where V is the number of nodes and E is the number of links. Ignore stale queue entries when their stored distance no longer matches the best known distance.

Relate it to real networks carefully

This exercise is a useful model for weighted path search, but real Internet routing does not simply run Dijkstra over a complete map of per-link latency. Routes are selected by routing protocols and policy, paths can change, and delay depends on queuing and congestion as well as propagation. The problem isolates one algorithmic question: given a graph and fixed nonnegative edge weights, what is the shortest path from one source?

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.

Not started

Sign in to save your learning progress.

Sign in to save