Network Delay Time (LeetCode 743): Solution and Explanation

Medium
Depth First Search
Breadth First Search
Graph
Heap
Shortest Path

A network has n nodes and directed edges with travel times. A signal starts at node k, and you must report how long it takes until every node has received it, or -1 if some node can never be reached.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A node receives the signal at the moment the fastest path from k reaches it, and the whole network is done when the slowest of those fastest arrivals happens. So the answer is the maximum, over all nodes, of the shortest path distance from k. If any node is unreachable, the answer is -1.

That is a single-source shortest path problem with non-negative weights, which is exactly Dijkstra's algorithm. A plain BFS would only work if every edge took the same time. Bellman-Ford would also work, relaxing every edge n - 1 times, but its O(n × E) cost is unnecessary when no weights are negative.

Dijkstra's key insight is that if you always expand the unsettled node with the smallest tentative time, that time is final, because any other route would go through a node that is already at least as far away and weights cannot shrink the total. With a min-heap of (time, node) pairs you pop nodes in arrival order. The first time a node is popped, it is settled; later pops of the same node are stale and skipped. Because nodes are settled in increasing time, the last settled node's time is the answer.

Approach: Dijkstra's algorithm with a min-heap

  1. Build an adjacency list mapping each node u to its (v, w) outgoing edges.
  2. Push (0, k) onto the heap and create an empty visit set and t = 0.
  3. Pop the smallest (w1, n1). If n1 is already visited, skip it.
  4. Mark n1 visited and set t = max(t, w1), the latest settled arrival so far.
  5. For every edge (n2, w2) from n1 to an unvisited node, push (w1 + w2, n2).
  6. When the heap is empty, return t if all n nodes were visited, otherwise -1.

Step-by-step example

times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
  1. The heap starts as [(0, 2)]. Popping it settles node 2 at time 0 and pushes (1, 1) and (1, 3).
  2. Popping (1, 1) settles node 1 at time 1, so t = 1. Node 1 has no outgoing edges.
  3. Popping (1, 3) settles node 3 at time 1 and pushes (2, 4).
  4. Popping (2, 4) settles node 4 at time 2, so t = 2.
  5. The heap is empty and all 4 nodes are visited, so the answer is 2.

Code: Python, Java, C++

1class Solution:
2    def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
3        adj = collections.defaultdict(list)
4        for u, v, w in times:
5            adj[u].append((v, w))
6            
7        minH = [(0, k)]
8        visit = set()
9        t = 0
10        
11        while minH:
12            w1, n1 = heapq.heappop(minH)
13            if n1 in visit:
14                continue
15            visit.add(n1)
16            t = max(t, w1)
17            
18            for n2, w2 in adj[n1]:
19                if n2 not in visit:
20                    heapq.heappush(minH, (w1 + w2, n2))
21                    
22        return t if len(visit) == n else -1

Time and space complexity

Time

O(E log E)

Each edge can push one entry onto the heap, and every push and pop costs O(log E), which is the same as O(E log V) up to a constant.

Space

O(V + E)

The adjacency list stores every edge, the heap can hold up to E entries, and the visited set holds V nodes.

Other approaches

Bellman-Ford (time O(V × E), space O(V))

Initialize distances to infinity except the source and relax every edge n - 1 times. Slower, but it also works with negative edge weights, which this problem does not have.

Dijkstra with an array (no heap) (time O(V²), space O(V + E))

Keep a distance array and pick the closest unsettled node by linear scan each round. With at most 100 nodes this is simple and fast, and it is optimal for dense graphs.

Common mistakes

  • Treating the graph as undirected by adding reverse edges, which lets the signal travel backward along one-way links.
  • Returning the time of the last popped heap entry instead of the maximum settled time; stale entries can be popped later with larger or smaller values.
  • Not skipping already visited nodes on pop, which re-expands nodes and can update t with a non-shortest time.
  • Forgetting that nodes are labeled 1 to n, so a 0-indexed array of size n is off by one.

Frequently asked questions

Why use Dijkstra for network delay time?

You need the shortest arrival time from one source to every node, and all edge times are non-negative. That is the exact setting Dijkstra's algorithm is designed for.

Why is the answer the maximum shortest distance?

Every node gets the signal at its own shortest arrival time, and the network is only done when the last node is reached. So the answer is the largest of those times.

When does network delay time return -1?

If some node is never popped from the heap, it cannot be reached from k, and the signal never arrives there. The code checks this by comparing the visited count with n.

Can BFS solve it?

Plain BFS only finds shortest paths when every edge has the same weight. With different travel times you need Dijkstra, or a BFS variant that re-queues nodes whenever their time improves, which is slower.