Skip to content

Network Delay Time

Find when a signal from one node reaches the last node of a weighted, one-way network.

MediumShortest Paths
Solve on LeetCode

The problem

A network has n nodes labelled 1 to n, and each entry [u, v, w] in times is a one-way link: a signal sent from u arrives at v after w time units. A signal starts at node k. Return the time at which the last node receives it, or -1 if some node never does.

Input times = [[1, 2, 4], [1, 3, 1], [3, 2, 2], [2, 4, 1]], n = 4, k = 1

Output 4

Node 3 hears at time 1, node 2 at time 3 (through node 3, faster than the direct link of 4) and node 4 at time 4.

Input times = [[1, 2, 3], [3, 1, 2]], n = 3, k = 1

Output -1

Node 3 can send to node 1, but no link leads into node 3, so it never hears the signal.

Key constraint: Link times are never negative (0 to 100), which is exactly what Dijkstra's algorithm needs.

How to spot the pattern

  • You need the shortest travel time from one source to every node.
  • Links have different non-negative weights, so counting links with plain BFS is not enough.
  • The answer is decided by the farthest node: the largest of all the shortest times.

The idea

The signal reaches each node along that node's fastest route, so you need the shortest time from k to every node, and the answer is the largest of them. Dijkstra's algorithm finds these times by always settling the closest node that is not settled yet: with no negative weights, no route found later can beat it. A min-heap hands you that closest node quickly.

Brute force: Relax every link again and again until no time improves (Bellman-Ford), which takes O(n * E) time.

Step by step

  1. 1Build an adjacency list that maps each node u to its pairs (v, w).
  2. 2Set every time to infinity except dist[k] = 0, and push (0, k) onto a min-heap.
  3. 3Pop the smallest (d, u), and skip it if d is larger than dist[u], because that entry is out of date.
  4. 4For each link (v, w) out of u, if d + w < dist[v], set dist[v] = d + w and push (dist[v], v).
  5. 5When the heap is empty, return the largest value in dist, or -1 if any node is still at infinity.

See the pattern move

The shortest paths pattern on a small example. Step through it, or press play.

Code

import heapq


class Solution:
    def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
        graph = [[] for _ in range(n + 1)]  # graph[u] = list of (v, w)
        for u, v, w in times:
            graph[u].append((v, w))

        dist = [float("inf")] * (n + 1)
        dist[k] = 0
        heap = [(0, k)]  # (time, node), smallest time first
        while heap:
            d, u = heapq.heappop(heap)
            if d > dist[u]:
                continue  # an old entry; u was already reached faster
            for v, w in graph[u]:
                if d + w < dist[v]:
                    dist[v] = d + w
                    heapq.heappush(heap, (dist[v], v))

        slowest = max(dist[1:])
        return slowest if slowest < float("inf") else -1

Complexity

Time

O(n + E log E)

Space

O(n + E)

Each of the E links can push one heap entry, and each push or pop costs O(log E); the adjacency list stores every link.

Watch out for

  • Using plain BFS: it counts links instead of adding up time, and gets the first example wrong.
  • Returning the time of one node, or the sum of all times, instead of the largest shortest time.
  • Forgetting that nodes are labelled from 1, so arrays need size n + 1 (or every label needs a minus 1).

Follow-up questions

What if some link times could be negative?

Dijkstra can then settle a node too early. Bellman-Ford, which relaxes every link n - 1 times, still works and can also detect a negative cycle.

What if almost every pair of nodes has a link?

With E close to n^2, a simple O(n^2) Dijkstra that scans an array for the closest unsettled node, with no heap, is just as fast and shorter to write.

In Hinglish

Har baar heap se sabse paas wala node nikalo aur uske padosiyon ka time sudhaaro. End mein sabse bada time hi jawab hai, aur koi node infinity par reh gaya toh -1.

Related problems