Network Delay Time
Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #743
times[i] = [u, v, w] is a directed edge from u to v that takes w time. A signal starts at node k. Return the time until all n nodes (labeled 1..n) have received it, or -1 if some node never does.
Examples
text
times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2 → 2
times = [[1,2,1]], n = 2, k = 2 → -1Hints
- Each node receives the signal at its shortest-path distance from k.
- Non-negative weights point to Dijkstra. The answer is the maximum of those distances.
Approach
Dijkstra with a min-heap:
text
dist = {}; heap = [(0, k)]
while heap:
d, u = pop
if u in dist: continue # stale entry (lazy deletion)
dist[u] = d
for (v, w) in adj[u]: if v not in dist: push (d + w, v)
return max(dist.values()) if len(dist) == n else -1Lazy deletion (skipping already-finalized nodes when popped) avoids needing a decrease-key operation, which binary heaps don't support. The cost is O(E log E) = O(E log V). Dijkstra is correct only for non-negative weights. With negative weights, use Bellman-Ford.
Complexity
Time: O(E log V) with a heap (O(V²) with the array scan). Space: O(V + E).
Python solution
import heapq
from collections import defaultdict
def networkDelayTime(times, n, k):
adj = defaultdict(list)
for u, v, w in times:
adj[u].append((v, w))
dist, heap = {}, [(0, k)]
while heap:
d, u = heapq.heappop(heap)
if u in dist:
continue
dist[u] = d
for v, w in adj[u]:
if v not in dist:
heapq.heappush(heap, (d + w, v))
return max(dist.values()) if len(dist) == n else -1JavaScript solution
function networkDelayTime(times, n, k) {
const adj = Array.from({ length: n + 1 }, () => []);
for (const [u, v, w] of times) adj[u].push([v, w]);
const dist = new Array(n + 1).fill(Infinity), done = new Array(n + 1).fill(false);
dist[k] = 0;
// O(V^2) Dijkstra: n ≤ 100, so scanning for the closest unfinished node is simple and fast.
for (let it = 0; it < n; it++) {
let u = -1;
for (let i = 1; i <= n; i++) if (!done[i] && (u === -1 || dist[i] < dist[u])) u = i;
if (dist[u] === Infinity) break;
done[u] = true;
for (const [v, w] of adj[u]) if (dist[u] + w < dist[v]) dist[v] = dist[u] + w;
}
const ans = Math.max(...dist.slice(1));
return ans === Infinity ? -1 : ans;
}