0:00 / 0:00

How long until a signal reaches every tower? Dijkstra's algorithm settles the earliest arrival first, using a min-heap.

▼

The problem

LeetCode 743 (Medium). There are n nodes and a list of directed edges (u, v, w): a signal takes w time to travel from u to v. Send a signal from node k. Return the time it takes for all n nodes to receive it, or -1 if some node never does.

Example (the original's, made for the video): n = 5, k = 1, edges (1,2,1) (1,3,4) (2,3,2) (2,4,6) (3,5,3). The direct cable 1→3 takes 4, but 1→2→3 takes 1 + 2 = 3.

def network_delay(times, n, k):
    graph = defaultdict(list)
    for u, v, w in times:
        graph[u].append((v, w))
    best = {k: 0}
    heap, done = [(0, k)], set()
    while heap:
        t, node = heappop(heap)
        if node in done: continue
        done.add(node)
        for nxt, w in graph[node]:
            if t + w < best.get(nxt, inf):
                best[nxt] = t + w
                heappush(heap, (t + w, nxt))
    return max(best.values()) if len(done) == n else -1
TRY IT ON LEETCODE ▶

The solution

def network_delay(times, n, k):
    graph = defaultdict(list)
    for u, v, w in times:
        graph[u].append((v, w))
    best = {k: 0}
    heap, done = [(0, k)], set()
    while heap:
        t, node = heappop(heap)
        if node in done: continue
        done.add(node)
        for nxt, w in graph[node]:
            if t + w < best.get(nxt, inf):
                best[nxt] = t + w
                heappush(heap, (t + w, nxt))
    return max(best.values()) if len(done) == n else -1

Transcript

Network Delay Time. Towers are linked by one-way cables, each taking a set time to carry a signal. A signal starts at one tower. How long until every tower hears it? If some tower never does, return minus one.

Here are five towers, starting at tower one. The cable from one to three takes four. But one to two takes one, and two to three takes two, so the detour reaches three sooner, at three. The direct cable isn't always fastest.

You could try every route from tower one and keep the fastest to each tower. Here that's six routes, but every fork can double the count, so on big networks the routes explode.

Dijkstra's algorithm does better. Keep a min heap of arrival times, and always settle the earliest tower first. Its time is final: cables never take negative time, so any other route leaves from a tower reached no sooner, and can't arrive earlier. Then send the signal down its cables, and update every time that improves.

In code, list each tower's cables, and start the heap with time zero at the source. Pop the earliest time and tower. If it's already settled, skip it. Otherwise settle it, and push each neighbor whose time improves. At the end, the answer is the largest time, or minus one if a tower never settled.

Let's run it. Tower one settles at zero, giving two a time of one, and three a time of four. Two is earliest, so it settles at one. Through two, three improves from four to three, and four gets seven. Three settles at three, and five gets six. Next the heap pops three's old entry. Three is already settled, so it's stale: skip it. Five settles at six. Four settles last, at seven: the answer.

Each cable pushes at most once, and each heap step costs log V. With building the graph, that's V plus E, times log V time, and V plus E space.

Settle the earliest, spread along its cables, repeat. That's Network Delay Time.