Problem
You have n nodes labeled from 1 to n, and directed edges times[i] = [u, v, w] meaning a signal takes w time to go from u to v. A signal starts at node k. Return the time when every node has received the signal, or -1 if it is impossible.
Original: LeetCode 743: Network Delay Time.
Examples
Example 1
`times = [[2, 1, 1], [2, 3, 1], [3, 4, 1]], n = 4, k = 2``2`Example 2
`times = [[1, 2, 1]], n = 2, k = 1``1`Example 3
`times = [[1, 2, 1]], n = 2, k = 2``-1`Constraints
1 <= k <= n <= 1001 <= times.length <= 6000times[i].length == 31 <= ui, vi <= nui != vi0 <= wi <= 100- All the pairs
(ui, vi)are unique. (i.e., no multiple edges.)
Hints
Hint 1
Weights are positive, so Dijkstra is the right shortest-path algorithm. The time for the whole network is the last arrival, not the sum of the edges.
Hint 2
Single-source shortest paths on a positive weighted directed graph: Dijkstra.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Bellman-Ford is also correct and easier to type, but it is O(n E). An unweighted BFS is wrong because edge times differ.
Optimal. Build the adjacency list, then Dijkstra with a min-heap. Skip stale heap entries when a better time is already known.
Alternative. If n is tiny, you can use Floyd-Warshall and read the k-th row.
Complexity
- Time
- O((n + E)
log n)
- Space
- O(n + E)
Code
import heapq
from collections import defaultdict
def network_delay_time(times: list[list[int]], n: int, k: int) -> int:
graph = defaultdict(list)
for u, v, w in times:
graph[u].append((v, w))
dist = {k: 0}
heap = [(0, k)]
while heap:
time, u = heapq.heappop(heap)
if time > dist.get(u, 10**18):
continue
for v, w in graph[u]:
cand = time + w
if cand < dist.get(v, 10**18):
dist[v] = cand
heapq.heappush(heap, (cand, v))
if len(dist) < n:
return -1
return max(dist.values())
if __name__ == "__main__":
assert network_delay_time([[2, 1, 1], [2, 3, 1], [3, 4, 1]], 4, 2) == 2
assert network_delay_time([[1, 2, 1]], 2, 1) == 1
assert network_delay_time([[1, 2, 1]], 2, 2) == -1
print("ok")import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
public class NetworkDelayTime {
static int networkDelayTime(int[][] times, int n, int k) {
List<List<int[]>> graph = new ArrayList<>();
for (int i = 0; i <= n; i++) graph.add(new ArrayList<>());
for (int[] e : times) graph.get(e[0]).add(new int[] {e[1], e[2]});
int[] dist = new int[n + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[k] = 0;
var heap = new PriorityQueue<int[]>((a, b) -> Integer.compare(a[0], b[0]));
heap.offer(new int[] {0, k});
while (!heap.isEmpty()) {
int[] cur = heap.poll();
int time = cur[0], u = cur[1];
if (time > dist[u]) continue;
for (int[] e : graph.get(u)) {
int v = e[0], w = e[1];
if (time + w < dist[v]) {
dist[v] = time + w;
heap.offer(new int[] {dist[v], v});
}
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (dist[i] == Integer.MAX_VALUE) return -1;
if (dist[i] > ans) ans = dist[i];
}
return ans;
}
public static void main(String[] args) {
if (networkDelayTime(new int[][] {{2, 1, 1}, {2, 3, 1}, {3, 4, 1}}, 4, 2) != 2) throw new AssertionError();
if (networkDelayTime(new int[][] {{1, 2, 1}}, 2, 1) != 1) throw new AssertionError();
if (networkDelayTime(new int[][] {{1, 2, 1}}, 2, 2) != -1) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: times [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2 returns 2; [[1,2,1]], n = 2, k = 1 returns 1; the same edge starting at 2 returns -1.
- I used 10^18 only as a stand-in for "unknown" in the Python dictionary, not as a claimed input bound.
Follow-ups
- If some weights could be negative, Dijkstra is wrong and you need Bellman-Ford.
- Cheapest Flights Within K Stops adds a hop limit, so you have to track depth as well as cost.
Interview script
"This is Dijkstra from k. The network is ready when the last node is reached, so I return the maximum shortest-path distance, or -1 if a node is unreachable."
Source: LeetCode 743: Network Delay Time Source: Java SE 17 API: PriorityQueue
Sources (2)
- LeetCode 743: Network Delay Timeleetcode.com
- Java SE 17 API: PriorityQueuedocs.oracle.com