CodeArchon

mediumAdvanced GraphsAmazonFacebook

Signal Broadcast Timer

A master clock sends a sync pulse from node k through a directed, weighted comm mesh. Return the moment every node has received the pulse.

Given n nodes labeled 1..n and times[i] = [u, v, w], return the minimum time for a signal from k to reach ALL nodes, or -1 if impossible.

Choose approach

1
2
u
3
4
1/5
Narrationstep 1 of 5

Settle node 2 at distance 0.

1import heapq
2def networkDelayTime(times, n, k):
3 adj = [[] for _ in range(n + 1)]
4 for u, v, w in times: adj[u].append((v, w))
5 dist = [float('inf')] * (n + 1); dist[k] = 0
6 pq = [(0, k)]
7 while pq:
8 d, u = heapq.heappop(pq)
9 if d > dist[u]: continue
10 for v, w in adj[u]:
11 if d + w < dist[v]:
12 dist[v] = d + w
13 heapq.heappush(pq, (dist[v], v))
14 m = max(dist[1:])
15 return -1 if m == float('inf') else m
Variables
u=2
dist=0

How to think about it

  1. Minimum broadcast time = longest shortest-path from k.
  2. Priority queue extracts the current closest node.
  3. Infinity in any dist entry -> unreachable.

Edge cases to catch in interview

  • Single node -> 0.
  • Unreachable node -> -1.

Examples

Example 11
{"n":2,"k":1,"times":[[1,2,1]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed