The problem, in one line. Given one-way links with travel times, send a signal from one computer and report when the last computer hears it, or -1 if one never does. LeetCode 743.
The tell. Links have different lengths and you want the earliest arrival at every point, not just one. “How long until everyone has it” is the largest of all the shortest times.
The wrong first idea
Count links, not seconds. Use the plain queue from the last problem and take the route with the fewest hops.
On the map in the calls below, from town 1 to town 5 the fewest-hops route is 1, 3, 4, 5. It costs 1 + 5 + 3 = 9. The fast route is 1, 3, 2, 4, 5 and costs 1 + 2 + 1 + 3 = 7, one hop longer. Fewest hops answers “how few?”, and the question here is “how soon?”.
The invariant
This card is the one-page summary of Clinic #25: Network Delay Time, which builds it step by step. Keep a heap of (time so far, town). Pop the smallest, and if that town is new, its time is final.
pop (0, 1): town 1 done at 0, push 2 at 4 and 3 at 1
pop (1, 3): town 3 done at 1, push 2 at 3 and 4 at 6
pop (3, 2): town 2 done at 3, push 4 at 4 (the 4 at town 2 later is stale)
The sentence that stays true every step: the first time a town comes off the heap, its time is final. Any other way to reach it would have to pass through something still waiting in the heap, and that is already no sooner.
The solution
import heapq
def network_delay(times, n, k):
graph = {i: [] for i in range(1, n + 1)}
for u, v, w in times:
graph[u].append((v, w))
dist = {}
heap = [(0, k)]
while heap:
d, u = heapq.heappop(heap)
if u in dist:
continue
dist[u] = d # first pop of a node is its shortest time
for v, w in graph[u]:
if v not in dist:
heapq.heappush(heap, (d + w, v))
return max(dist.values()) if len(dist) == n else -1
edges = [(1, 2, 4), (1, 3, 1), (3, 2, 2), (2, 4, 1), (3, 4, 5), (4, 5, 3)]
print(network_delay(edges, 5, 1))
print(network_delay(edges, 5, 4))
print(network_delay(edges, 5, 5))
7
-1
-1
type item struct{ d, u int }
type pq []item
func (p pq) Len() int { return len(p) }
func (p pq) Less(i, j int) bool { return p[i].d < p[j].d }
func (p pq) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p *pq) Push(x any) { *p = append(*p, x.(item)) }
func (p *pq) Pop() any { o := *p; x := o[len(o)-1]; *p = o[:len(o)-1]; return x }
func networkDelay(times [][]int, n, k int) int {
graph := map[int][][2]int{}
for _, t := range times {
graph[t[0]] = append(graph[t[0]], [2]int{t[1], t[2]})
}
dist := map[int]int{}
h := &pq{{0, k}}
for h.Len() > 0 {
cur := heap.Pop(h).(item)
if _, ok := dist[cur.u]; ok {
continue
}
dist[cur.u] = cur.d // first pop of a node is its shortest time
for _, e := range graph[cur.u] {
if _, ok := dist[e[0]]; !ok {
heap.Push(h, item{cur.d + e[1], e[0]})
}
}
}
best := 0
for _, d := range dist {
best = max(best, d)
}
if len(dist) != n {
return -1
}
return best
}
Same three calls print 7, -1, -1. The Go needs container/heap imported.
Complexity
- Time O(e log e): each link can push once, and every push and pop on the heap costs a logarithm.
- Space O(n + e): the graph, the finished times and the heap.
Traps
- Counting hops. The map above gives 9 for the fewest-hops route when the true answer is 7.
- Returning the largest time without checking that every town was reached. Starting at town 5, which has no outgoing link, the loop finishes a single town at 0 and would answer 0 instead of -1.
- Sizing arrays to
nwhen towns are numbered 1 to n. Town 5 of 5 then falls off the end, so usen + 1or a map.
Next in the ladder
Path With Minimum Effort keeps the heap but changes what a route costs: not the sum of its steps, only its single worst step.