LeetCode #743 Medium

Network Delay Time

Network Delay Time is LeetCode 743 (Medium). A network has n nodes labelled 1 to n, and a list times of directed edges [u, v, w]: a signal sent from u reaches v after w time units.

A signal is sent from node k. Return the time it takes for all n nodes to receive it, or -1 if some node can never receive it.

  • Every time w is between 0 and 100, so none is negative.
  • n is at most 100 and there are at most 6,000 edges.
Constraints
  • 1 <= k <= n <= 100
  • 1 <= times.length <= 6000
  • times[i] = [u, v, w], 1 <= u, v <= n, u != v
  • 0 <= w <= 100 — no negative times
  • No two edges share the same (u, v) pair
graphdijkstrashortest-path
Open on LeetCode ↗
02

Intuition

The signal spreads along every edge at once, so each node first hears it at its shortest travel time from k. The whole network has heard it when the last node does.

  • Each node: the earliest arrival is the shortest-path distance from k.
  • The answer: the largest of those distances, because that node is the last to hear.
  • Unreachable: if some node has no path from k, it never hears, and the answer is -1.

So this is one run of Dijkstra's algorithm from k, followed by a maximum. Dijkstra fits because no time is negative: the closest unfinished node can never be reached sooner by a longer detour.

How to spot this pattern

"How long until everyone is reached" on a weighted graph means: shortest distance from the source to every node, then the maximum, because the signal travels every route at once and the network is done when the last node hears it. This problem is the standard example. With non-negative weights that is Dijkstra; with all weights equal, plain BFS is enough.

03

Approach

Try it first

Before reading on: on the second example, when does node 2 first receive the signal? Why can't BFS, which counts hops, give the right time when edges have different weights?

1

Build the graph one way only

For each [u, v, w], add (v, w) to graph[u]. The edges are directed, so do not add the reverse edge: that would invent routes the network does not have.

2

Start Dijkstra at k

Set dist[k] = 0 and every other dist to infinity. Push (0, k) onto a min-heap. The heap always gives back the node with the smallest arrival time found so far.

3

Pop the earliest arrival

Pop (d, u):

  • if d > dist[u], a faster route to u was found after this entry was pushed, so skip it;
  • otherwise d is the final arrival time of u, because any other route would leave through a node that is reached no earlier, and times never go down.
4

Relax the edges out of u

For each (v, w) in graph[u], if d + w < dist[v], the signal reaches v sooner through u. Set dist[v] = d + w and push (dist[v], v).

5

Take the latest arrival

When the heap is empty, dist holds every arrival time. If any dist is still infinity, that node never hears the signal, so return -1. Otherwise return the largest dist.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
▶3 graph = defaultdict(list)
▶4 for u, v, w in times:
▶5 graph[u].append((v, w))
▶6 dist = [float("inf")] * (n + 1)
▶7 dist[k] = 0
▶8 heap = [(0, k)]
▶9 while heap:
▶10 d, u = heapq.heappop(heap)
▶11 if d > dist[u]:
▶12 continue
▶13 for v, w in graph[u]:
▶14 if d + w < dist[v]:
▶15 dist[v] = d + w
▶16 heapq.heappush(heap, (dist[v], v))
▶17 ans = max(dist[1:])
▶18 return ans if ans < float("inf") else -1
11112start34time012dist1∞203∞4∞heap0node 2signal leaves node 2 at time 0
dist[2]0the start
heap(0, 2)
Start. Only node 2 has the signal, at time 0. Every other arrival time is unknown (infinity) until an edge reaches it.
11112start34time0122dist1∞203∞4∞heapemptynode 2 hears the signal at time 0
u2earliest in the heap
arrival0final
edges out2
Node 2 is done at time 0. It is the earliest arrival left in the heap, and since no edge takes negative time, no other route can reach it sooner. Now try each of its 2 outgoing edges.
11112start34time0122dist11203∞4∞heap1node 12 → 1: 0 + 1 = 1
edge2 → 1time 1
dist[1]∞ → 1
heap(1, 1)
Node 1 had no known time. Through 2 the signal gets there at 0 + 1 = 1; record it and push it.
11112start34time0122dist1120314∞heap1node 11node 32 → 3: 0 + 1 = 1
edge2 → 3time 1
dist[3]∞ → 1
heap(1, 1) (1, 3)
Node 3 had no known time. Through 2 the signal gets there at 0 + 1 = 1; record it and push it.
11112start34time01212dist1120314∞heap1node 3node 1 hears the signal at time 1
u1earliest in the heap
arrival1final
edges out0
Node 1 is done at time 1. It is the earliest arrival left in the heap, and since no edge takes negative time, no other route can reach it sooner. It has no outgoing edges, so it passes the signal nowhere.
11112start34time012123dist1120314∞heapemptynode 3 hears the signal at time 1
u3earliest in the heap
arrival1final
edges out1
Node 3 is done at time 1. It is the earliest arrival left in the heap, and since no edge takes negative time, no other route can reach it sooner. Now try each of its 1 outgoing edge.
11112start34time012123dist11203142heap2node 43 → 4: 1 + 1 = 2
edge3 → 4time 1
dist[4]∞ → 2
heap(2, 4)
Node 4 had no known time. Through 3 the signal gets there at 1 + 1 = 2; record it and push it.
11112start34time0121234dist11203142heapemptynode 4 hears the signal at time 2
u4earliest in the heap
arrival2final
edges out0
Node 4 is done at time 2. It is the earliest arrival left in the heap, and since no edge takes negative time, no other route can reach it sooner. It has no outgoing edges, so it passes the signal nowhere.
11112start34time0121234dist11203142heapemptylast arrival: node 4 at 2 → return 2
result2latest arrival
Answer 2. Every node has heard the signal, and the last one is node 4 at time 2. The green edges show the route each node was reached by.
05

Bellman-Ford version

Start with dist[k] = 0. Each pass checks every edge u → v and lowers dist[v] to dist[u] + w if that is smaller. A shortest path uses at most n - 1 edges, so n - 1 passes are enough; stop early when a pass changes nothing.

▶1class Solution:
▶2 def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
▶3 dist = [float("inf")] * (n + 1)
▶4 dist[k] = 0
▶5 for _ in range(n - 1):
▶6 changed = False
▶7 for u, v, w in times:
▶8 if dist[u] + w < dist[v]:
▶9 dist[v] = dist[u] + w
▶10 changed = True
▶11 if not changed:
▶12 break
▶13 ans = max(dist[1:])
▶14 return ans if ans < float("inf") else -1
06

Common pitfalls

Adding each edge in both directions

✗ Wrong
graph[u].append((v, w))
graph[v].append((u, w))
✓ Right
graph[u].append((v, w))

A signal can only travel from u to v. The reverse edge creates shortcuts that do not exist, so the answer can come out too small, or a node that should be unreachable looks reachable.

Counting hops instead of time

✗ Wrong
# BFS: every edge counts as 1
heappush(heap, (d + 1, v))
✓ Right
heappush(heap, (d + w, v))

The route with the fewest edges is not always the fastest. In the second example, the direct edge 1 → 2 takes 4, but 1 → 3 → 2 takes only 3.

Including node 0 in the maximum

✗ Wrong
return max(dist)
✓ Right
return max(dist[1:])

Nodes are labelled from 1, so dist[0] is an unused slot that stays at infinity. Including it makes every answer -1.

07

Edge cases

A node no edge leads to

Its dist stays at infinity, so the answer is -1 even if every other node is reached, as in the third example.

08

Complexity

Time
O(E log E)
Space
O(n + E)
Each edge can push one heap entry, so there are at most E pushes and pops, each costing O(log E). The graph and the heap take O(n + E) memory. With n ≤ 100 and E ≤ 6,000 this is tiny.
09

Network Delay Time FAQ

How does the Dijkstra solution work?
  • Graph: directed adjacency list, graph[u] = [(v, w), ...].
  • Start: dist[k] = 0, heap = [(0, k)].
  • Loop: pop (d, u); skip if d > dist[u]; for each edge, if d + w < dist[v], update dist[v] and push it.
  • Answer: max(dist[1..n]), or -1 if any is infinity.
  • Complexity: O(E log E) time, O(n + E) space.