743. Network Delay Time
Asked at 10Google38Amazon28Bloomberg22Microsoft20Meta15Nvidia48Akuna Capital97Netflix69Salesforce41Cisco37
Problem
A network has nodes 1…n and directed edges times[i] = [u, v, w]: a signal takes w time to travel from u to v. Send a signal from node k and return how long it takes for every node to receive it, or −1 if some node never does.
Example: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2 → 2
Constraints: n ≤ 100; up to 6000 edges.
Dijkstra from k; answer = max shortest distance, or −1 if some node is unreachable.
Complexity: O(E log V).
class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
g = defaultdict(list)
for u, v, w in times:
g[u].append((v, w))
dist = {}
pq = [(0, k)]
while pq:
d, u = heappop(pq)
if u in dist:
continue
dist[u] = d
for v, w in g[u]:
if v not in dist:
heappush(pq, (d + w, v))
return max(dist.values()) if len(dist) == n else -1
assert Solution().networkDelayTime([[2, 1, 1], [2, 3, 1], [3, 4, 1]], 4, 2) == 2
assert Solution().networkDelayTime([[1, 2, 1]], 2, 2) == -1
class Solution {
public int networkDelayTime(int[][] times, int n, int k) {
List<List<int[]>> g = new ArrayList<>();
for (int i = 0; i <= n; i++) g.add(new ArrayList<>());
for (int[] t : times) g.get(t[0]).add(new int[]{t[1], t[2]});
int[] dist = new int[n + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[k] = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); // {dist, node}
pq.add(new int[]{0, k});
while (!pq.isEmpty()) {
int[] cur = pq.poll();
int d = cur[0], u = cur[1];
if (d > dist[u]) continue;
for (int[] e : g.get(u))
if (d + e[1] < dist[e[0]]) { dist[e[0]] = d + e[1]; pq.add(new int[]{dist[e[0]], e[0]}); }
}
int best = 0;
for (int i = 1; i <= n; i++) best = Math.max(best, dist[i]);
return best == Integer.MAX_VALUE ? -1 : best;
}
}
type distHeap [][2]int // (distance, node), smallest distance first
func (h distHeap) Len() int { return len(h) }
func (h distHeap) Less(i, j int) bool { return h[i][0] < h[j][0] }
func (h distHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *distHeap) Push(x any) { *h = append(*h, x.([2]int)) }
func (h *distHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func networkDelayTime(times [][]int, n int, k int) int {
g := make([][][2]int, n+1) // u -> (v, w)
for _, t := range times {
g[t[0]] = append(g[t[0]], [2]int{t[1], t[2]})
}
dist := map[int]int{} // finalized nodes
pq := &distHeap{{0, k}}
for pq.Len() > 0 {
top := heap.Pop(pq).([2]int)
d, u := top[0], top[1]
if _, done := dist[u]; done {
continue
}
dist[u] = d
for _, e := range g[u] {
if _, done := dist[e[0]]; !done {
heap.Push(pq, [2]int{d + e[1], e[0]})
}
}
}
if len(dist) < n {
return -1
}
best := 0
for _, d := range dist {
best = max(best, d)
}
return best
}