Network Delay Time

Medium Graphs Dijkstra Original on LeetCode

Network Delay Time is a medium graphs problem solved with the dijkstra pattern. The best approach, optimal (dijkstra with a min-heap), runs in O(E log V) time and O(V + E) space. Below are 2 approaches in Java, from bellman-ford up.

Problem

A signal is sent from node k through a network of n nodes. times[i] = [u, v, w] means the signal takes w time to travel from u to v. Return the time it takes for all nodes to receive the signal, or -1 if some node never does.

Examples

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 = 2
Output
-1
Why
Node 1 cannot be reached from 2.

Constraints

  • 1 <= n <= 100; times[i] = [u, v, w] is a directed edge with weight 1 to 100.
  • Nodes are numbered 1..n.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.

ApproachTimeSpace
Bellman-FordO(n · E)O(n)
Optimal (Dijkstra with a min-heap)O(E log V)O(V + E)

1Bellman-Ford

TimeO(n · E)
SpaceO(n)

Relax every edge n - 1 times. After that, dist holds the shortest distances. Simple, but slower than Dijkstra.

  1. dist[k] = 0, others infinity.
  2. Repeat n - 1 times: for each edge, dist[v] = min(dist[v], dist[u] + w).
  3. Answer = max dist, or -1 if any is infinity.
Java
class Solution {
    public int networkDelayTime(int[][] times, int n, int k) {
        int INF = Integer.MAX_VALUE / 2;
        int[] dist = new int[n + 1];
        Arrays.fill(dist, INF);
        dist[k] = 0;
        for (int r = 1; r < n; r++)
            for (int[] e : times)
                if (dist[e[0]] + e[2] < dist[e[1]]) dist[e[1]] = dist[e[0]] + e[2];
        int ans = 0;
        for (int i = 1; i <= n; i++) ans = Math.max(ans, dist[i]);
        return ans >= INF ? -1 : ans;
    }
}

2Optimal (Dijkstra with a min-heap)

TimeO(E log V)
SpaceO(V + E)

Always settle the closest unsettled node next. With non-negative weights, its distance can no longer improve. Relax its outgoing edges and push improved distances into the heap, skipping stale entries.

  1. Adjacency list; heap of {dist, node} starting with {0, k}.
  2. Poll; skip if the distance is stale; relax neighbours.
  3. Answer = max final distance, or -1 if any node is unreached.
Java
class Solution {
    public 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<>());
        for (int[] e : times) adj.get(e[0]).add(new int[] { e[1], e[2] });
        int[] dist = new int[n + 1];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[k] = 0;
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
        pq.add(new int[] { 0, k });
        while (!pq.isEmpty()) {
            int[] cur = pq.poll();
            int d = cur[0], u = cur[1];
            if (d > dist[u]) continue;
            for (int[] e : adj.get(u)) {
                int v = e[0], nd = d + e[1];
                if (nd < dist[v]) { dist[v] = nd; pq.add(new int[] { nd, v }); }
            }
        }
        int ans = 0;
        for (int i = 1; i <= n; i++) {
            if (dist[i] == Integer.MAX_VALUE) return -1;
            ans = Math.max(ans, dist[i]);
        }
        return ans;
    }
}

Edge cases to test

  • Unreachable nodes
  • Several edges between the same pair

Hints

Hint 1

The answer is the largest shortest-path distance from k. Weights are non-negative, so use Dijkstra.

FAQ

What is the best time complexity for Network Delay Time?

Optimal (Dijkstra with a min-heap) runs in O(E log V) time and O(V + E) extra space.

Which pattern does Network Delay Time use?

It is a graphs problem that uses the dijkstra pattern. Other problems with the same pattern: Find the City With the Smallest Number of Neighbors at a Threshold Distance.

Is there a brute force solution for Network Delay Time?

Yes. Bellman-Ford takes O(n · E) time and O(n) space. Relax every edge n - 1 times.

Which edge cases should I test for Network Delay Time?

Unreachable nodes; Several edges between the same pair.