Network Delay Time

Find how long a signal sent from one node takes to reach every node of a network, or -1 if some node never gets it.

A network has n nodes, labelled 1 to n. Each entry times[i] = [u, v, w] is a one-way link: a signal sent from node u reaches node v after w units of time, and no time is negative. A signal starts at node k. Return how long it takes until every node has received it, or -1 if some node never does.

Example 1
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2
Example 2
Input: times = [[1,2,1]], n = 2, k = 1
Output: 1
Example 3
Input: times = [[1,2,1]], n = 2, k = 2
Output: -1
Explanation: the only link leaves node 1, so a signal from node 2 cannot reach it.
Solution

The Idea

Imagine each node as a person, and each link as a one-way phone line that takes a fixed time to pass a message along. The moment a person hears the message, they pass it on along every line that leaves them. How long until the last person has heard it?

Look at the picture below, which draws Example 1. Each circle is a node, and each arrow is one entry of times: the entry [2,1,1] is the arrow from 2 to 1 labelled "time 1". Circles joined by one-way arrows that carry times like this form a directed weighted graph.

Example 1 as a picture: node 2 sends the signal. Arrows of time 1 lead from 2 to 1, from 2 to 3 and from 3 to 4. Nodes 1 and 3 hear it at time 1, and node 4 hears it at time 2, the last one.

Node 2, labelled "start: k = 2", has the signal at time 0. Both of its arrows take time 1, so nodes 1 and 3 hear it at time 1. Node 3 passes it on to node 4, which hears it at 1 + 1 = 2. Node 4, labelled "hears it at 2, the last one", is the last to hear, so the answer is 2.

In Example 1 each node can be reached in only one way. What happens when there are two ways? Take three nodes with links 1 to 2 of time 10, 1 to 3 of time 1, and 3 to 2 of time 1, and send from node 1. Along the direct link, the signal reaches node 2 at time 10. Through node 3, it gets there at 1 + 1 = 2.

Node 2 hears it at time 2, and the copy that arrives at time 10 changes nothing. So each node hears the signal along its fastest route, and the total time of that route is called its shortest distance from k. In Example 3, node 1 has no route from node 2 at all, so it never hears the signal.

That turns the problem into two smaller ones: find the shortest distance from k to every node, then take the largest of them, or -1 if some node has no route.

Solution Approach

Turning that idea into code means settling four things: how to store the links, in which order to handle the nodes (with a slow way and a faster way), what to do with an arrival that was beaten, and how to read off the answer.

Storing the links

How does the code find the links that leave a node? Searching all of times each time would repeat a lot of work. Instead, give every node its own list of the links that leave it, holding the node each link leads to and its time. A list of these lists is called an adjacency list.

For Example 1, node 2's list holds {1, 1} and {3, 1}, node 3's list holds {4, 1}, and the lists of nodes 1 and 4 are empty. The nodes are numbered from 1, so the code makes n + 1 lists and leaves list 0 unused.

The order of the nodes

Which node should pass the signal on next? Follow the clock. Keep, for every node, the earliest arrival time found so far, with "not reached yet" for the rest. Then always take the node with the smallest such time that has not been handled yet.

That node's time is already final. Any other route to it must pass through a node not handled yet, which is reached no earlier, and then add times that are not negative. Handling the node means checking each of its links: if a link gives the node at its other end an earlier arrival than the one stored, store the new time. This way of finding all shortest distances from one start node is called Dijkstra's algorithm, after the computer scientist Edsger Dijkstra.

How do we find the node with the smallest time? The simple way scans all n nodes for each node handled, which is about n2 steps in total. A faster way keeps the waiting arrivals in a min-heap, a structure that hands back its smallest item in about log m steps when it holds m items. Java's PriorityQueue works as one when its comparator, the rule it uses to order two entries, puts the smaller time first:

Java
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));

Each entry is a pair {node, arrival time}, so a[1] and b[1] are the two times being compared.

Arrivals that were beaten

What happens to a heap entry when a faster route to its node turns up later? Go back to the three-node network. Node 1 adds {2, 10} and {3, 1} to the heap. {3, 1} comes out first, and its link to node 2 gives time 2, so {2, 2} goes in too.

Now the heap holds two entries for node 2. Taking {2, 10} out of the middle of a PriorityQueue is slow, so the code leaves it there. When it comes out at last, its time 10 is larger than the stored 2, and the code skips it. Such a leftover is called a stale entry.

Reading off the answer

When the heap is empty, what do the stored times say? Each one is the shortest distance to that node. A node still marked "not reached yet" has no route from k, so the answer is -1. Otherwise the answer is the largest stored time, the moment the last node hears the signal.

Java Solution

The method networkDelayTime works in these steps:

  1. First, build the adjacency list adj: a list of n + 1 empty lists. For each entry t of times, add the pair {t[1], t[2]} to the list of node t[0].
  2. Create the array dist of the earliest arrival times, with n + 1 slots. Fill it with Integer.MAX_VALUE, which stands for "not reached yet", and set dist[k] to 0. Create the min-heap pq and add the entry {k, 0}.
  3. While pq is not empty, take out its earliest entry, top, with node u and time d. If d is larger than dist[u], the entry is stale, so skip it.
  4. Otherwise, go through each link e in the list of u, which leads to node v in time e[1]. If d + e[1] is smaller than dist[v], store it in dist[v] and add {v, dist[v]} to the heap.
  5. Finally, a loop goes over nodes 1 to n. If some dist[i] is still Integer.MAX_VALUE, return -1. Otherwise keep the largest time in answer and return it.

The main method runs the three examples, the three-node network with the slow direct link, a single node with no links, and a network where node 4 has a link out but none in.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;

public class NetworkDelayTime {

    public static int networkDelayTime(int[][] times, int n, int k) {
        List<List<int[]>> adj = new ArrayList<>();
        for (int i = 0; i <= n; i++) {
            adj.add(new ArrayList<>());               // slot 0 stays unused
        }
        for (int[] t : times) {
            adj.get(t[0]).add(new int[] {t[1], t[2]}); // from u: {v, w}
        }

        int[] dist = new int[n + 1];
        Arrays.fill(dist, Integer.MAX_VALUE);         // not reached yet
        dist[k] = 0;
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));
        pq.add(new int[] {k, 0});
        while (!pq.isEmpty()) {
            int[] top = pq.poll();                    // the earliest arrival waiting
            int u = top[0];
            int d = top[1];
            if (d > dist[u]) {
                continue;                             // an older, slower arrival
            }
            for (int[] e : adj.get(u)) {
                int v = e[0];
                if (d + e[1] < dist[v]) {
                    dist[v] = d + e[1];               // a faster way to reach v
                    pq.add(new int[] {v, dist[v]});
                }
            }
        }

        int answer = 0;
        for (int i = 1; i <= n; i++) {
            if (dist[i] == Integer.MAX_VALUE) {
                return -1;                            // node i never hears the signal
            }
            answer = Math.max(answer, dist[i]);       // the last node to hear it
        }
        return answer;
    }

    public static void main(String[] args) {
        System.out.println(networkDelayTime(new int[][] {{2, 1, 1}, {2, 3, 1}, {3, 4, 1}}, 4, 2));
        System.out.println(networkDelayTime(new int[][] {{1, 2, 1}}, 2, 1));
        System.out.println(networkDelayTime(new int[][] {{1, 2, 1}}, 2, 2));
        System.out.println(networkDelayTime(new int[][] {{1, 2, 10}, {1, 3, 1}, {3, 2, 1}}, 3, 1));
        System.out.println(networkDelayTime(new int[][] {}, 1, 1));
        System.out.println(networkDelayTime(new int[][] {{1, 2, 4}, {2, 3, 4}, {4, 1, 1}}, 4, 1));
    }
}

Running it prints:

Output
2
1
-1
2
0
-1

The answers 2, 1 and -1 on the opening lines match Examples 1, 2 and 3. Look at the fourth line, 2: in the three-node network, node 2 is reached through node 3 at time 2, not along the direct link at time 10, whose stale entry is skipped.

The fifth line is 0, because a single node already has the signal and nothing has to travel. The last line is -1: node 4's only link points from it to node 1, so no signal from node 1 ever reaches node 4.

Why does the last loop start at 1 and not at 0? Slot 0 of dist belongs to no node and keeps Integer.MAX_VALUE. With the loop starting at 0, the same main prints -1 on all six lines.

Complexity

The work is building the adjacency list, plus one heap push and one heap poll each time a link gives a node an earlier arrival. Here E is the number of links in times.

  • Time: O(n + E log E), because each link adds at most one entry to the heap, and each push or poll on a heap of up to E entries takes about log E steps.
  • Space: O(n + E), because the adjacency list keeps one pair per link, dist has n + 1 slots, and the heap can hold up to one entry per link, stale entries included.

The algorithm is explained step by step, with more pictures, in Dijkstra's Algorithm.