Network Delay Time solution explained
Network Delay Time asks how long a signal sent from one node takes to reach every node of a directed network with travel times on its links, or -1 if some node is never reached. Run Dijkstra's algorithm from the source to get the earliest arrival time at each node, then return the largest of those times. With a binary heap that is O(E log E); a simple array scan is O(V² + E).
By Evin JohnPublished 9 min read
The problem, in plain terms
A network has n servers labeled 1 to n. Some servers have one-way links to others, and each link takes a fixed number of milliseconds to carry a message. At time zero, one source server starts broadcasting: every server that receives the message immediately forwards it along all of its outgoing links. Return the time at which the last server receives the message. If some server can never receive it, return -1.
Network A: n = 4, source = 1
links (from, to, delay): (1,2,4) (1,3,1) (3,2,2) (2,4,3)
arrival: server 1 at 0, server 3 at 1, server 2 at 3, server 4 at 6
answer: 6
Network B: same links, but n = 5
server 5 has no incoming link answer: -1Network A holds the lesson. The direct link from 1 to 2 takes 4, but going through server 3 takes 1 + 2 = 3, so server 2 hears the message at time 3, not 4. Server 4 then hears it at 3 + 3 = 6, which is the latest arrival. The answer is not the sum of all delays and not the longest single link; it is the largest shortest-path distance.
Questions to settle first: are delays always zero or positive? Can there be two links between the same pair, or a link from a server to itself? How many servers and links are there? The first question decides the algorithm, and the last decides whether the heap or the array version is the better fit.
Why it shows up in interviews
This is a common way to check that you know Dijkstra's algorithm well enough to write it without notes, and that you understand its precondition. The twist at the end, taking a maximum over distances and spotting unreachable nodes, checks that you read the question rather than reciting a template. Expect to be asked why breadth-first search is not enough here and what would break with negative delays.
A slower baseline: Bellman-Ford
Start with the source at distance 0 and everything else at infinity. Sweep over every link and, if going through it gives its target a shorter time, update that target. A shortest path uses at most n - 1 links, so n - 1 full sweeps are always enough, and you can stop early when a sweep changes nothing.
def network_delay_slow(n, links, source):
INF = float("inf")
dist = [INF] * (n + 1)
dist[source] = 0
for _ in range(n - 1):
changed = False
for u, v, t in links:
if dist[u] + t < dist[v]:
dist[v] = dist[u] + t
changed = True
if not changed:
break
latest = max(dist[1:])
return -1 if latest == INF else latestIt is short and it tolerates negative delays as long as there is no negative loop, but it costs O(V × E). With non-negative delays you can do much better by always finishing the closest unfinished server first.
Optimal approach: Dijkstra's algorithm
Keep a min-heap of (time, server) pairs, starting with (0, source). Pop the smallest entry. If that server already has a final time, this entry is stale, so skip it. Otherwise its time is final: no route found later can be shorter, because every other route would have to leave from a server whose time is already at least as large, and delays never go below zero. Record it, then push each neighbor with the popped time plus the link's delay.
import heapq
def network_delay(n, links, source):
out = [[] for _ in range(n + 1)]
for u, v, t in links:
out[u].append((v, t))
final = [None] * (n + 1)
heap = [(0, source)]
while heap:
when, u = heapq.heappop(heap)
if final[u] is not None:
continue # a stale, slower entry for a finished server
final[u] = when
for v, t in out[u]:
if final[v] is None:
heapq.heappush(heap, (when + t, v))
arrivals = final[1:]
return -1 if None in arrivals else max(arrivals)Python's heapq has no decrease-key operation, so this version pushes a new entry whenever it finds a route and ignores older entries when they surface. The heap can therefore hold up to E entries, which is why the bound is O(E log E) rather than the O((V + E) log V) quoted for heaps that support decrease-key. Without parallel links E is at most V², so log E is at most twice log V and the difference is only a constant factor.
The array version for dense graphs
Without a heap, you can find the closest unfinished server by scanning all of them. That is O(V) per step and V steps, plus O(E) for relaxing links, so O(V² + E) in total. When the network is dense and E approaches V², this matches or beats the heap version and has less overhead. It is also handy in languages without a built-in priority queue, such as JavaScript.
function networkDelay(n, links, source) {
const out = Array.from({ length: n + 1 }, () => []);
for (const [u, v, t] of links) out[u].push([v, t]);
const dist = new Array(n + 1).fill(Infinity);
const done = new Array(n + 1).fill(false);
dist[source] = 0;
for (let step = 0; step < n; step++) {
let u = -1;
for (let x = 1; x <= n; x++) {
if (!done[x] && (u === -1 || dist[x] < dist[u])) u = x;
}
if (dist[u] === Infinity) break; // nothing else is reachable
done[u] = true;
for (const [v, t] of out[u]) {
if (dist[u] + t < dist[v]) dist[v] = dist[u] + t;
}
}
let latest = 0;
for (let x = 1; x <= n; x++) latest = Math.max(latest, dist[x]);
return latest === Infinity ? -1 : latest;
}Complexity summary
| Approach | Time | Extra space | Best when |
|---|---|---|---|
| Bellman-Ford | O(V × E) | O(V) | Delays can be negative |
| Dijkstra, binary heap, lazy deletion | O(E log E) | O(V + E) | Sparse networks |
| Dijkstra, array scan | O(V² + E) | O(V + E) | Dense networks |
| Floyd-Warshall, all pairs | O(V³) | O(V²) | Many different sources |
Edge cases to try
- A single server and no links: the answer is 0.
- A server with no incoming route from the source: -1.
- Two links between the same pair with different delays: the faster one wins.
- A link with delay 0: allowed, and Dijkstra still works.
- A link from a server to itself: harmless.
- A slow direct link beaten by a longer route with smaller delays.
Mistakes to avoid
- Using breadth-first search, which counts links rather than time and fails when delays differ.
- Returning the distance to one particular server, or the sum of distances, instead of the maximum.
- Treating a server as final when it is pushed onto the heap rather than when it is popped.
- Forgetting that servers are labeled from 1, so index 0 sneaks into the maximum.
- Not checking for unreachable servers, so infinity or a sentinel value is returned instead of -1.
Follow-ups
- Several sources start at once. Push all of them at time 0. That is a multi-source Dijkstra, and the code barely changes.
- Which server hears it last, and along what route? Store each server's predecessor when its time improves, then walk back from the latest one.
- When have at least m servers heard it? Sort the finite arrival times and take the m-th smallest.
- Some delays are negative. Dijkstra's argument breaks; use Bellman-Ford, and detect a negative loop by checking whether an n-th sweep still improves anything.
- The links are two-way. Add each link in both directions; nothing else changes.
How to explain it out loud
Fictional example
- Candidate
- Each server hears the message at the length of its shortest route from the source, so I need shortest paths from one source, and then the largest of them.
- Candidate
- All delays are non-negative, so Dijkstra works. I pop the server with the smallest tentative time from a heap; once popped, its time cannot improve, so I mark it final and push its neighbors.
- Candidate
- If any server never gets a final time, I return -1. Otherwise I return the maximum. With lazy deletion that is O(E log E).
- Interviewer
- Why not plain BFS?
- Candidate
- BFS finds the route with the fewest links. Here a route with three cheap links can beat one slow link, so I need the weights.
Related problems
Cheapest Flights Within K Stops adds a limit on how many links a route may use, which breaks plain Dijkstra in an instructive way. Word Ladder is the unweighted case, where breadth-first search alone is enough. Course Schedule works on a directed graph too, but asks about loops rather than distances. More shortest-path background is in the algorithm interview questions guide.
Practicing it with Natively
Dijkstra is one of those algorithms people half remember. During practice on Mac or Windows, Natively can read the network problem from a screenshot and outline the heap-based approach, including why the answer is a maximum and how to detect unreachable servers. Because it transcribes the mock session, you can reread whether you stated the non-negative delay condition before relying on it. See the AI interview assistant for how practice sessions work.
Questions people ask
How do you solve Network Delay Time?
Run Dijkstra's algorithm from the source to get each node's earliest arrival time. If any node is unreachable, return -1; otherwise return the largest arrival time.
Why is Dijkstra correct for Network Delay Time?
All delays are zero or positive, so once the node with the smallest tentative time is taken from the heap, no later route can reach it sooner. That is exactly the condition Dijkstra needs.
What is the time complexity of Network Delay Time?
Dijkstra with a binary heap and lazy deletion is O(E log E). The array-scan version is O(V² + E), which suits dense graphs. Bellman-Ford is O(V × E).
Can BFS solve Network Delay Time?
Not in general. Breadth-first search finds routes with the fewest links, but here links have different delays, so a route with more links can arrive earlier.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
