Network Delay Time

MediumGraphs · Shortest Path (Dijkstra)🧩 Shortest PathsLeetCode #743 ↗Updated

Problem

A network has nodes 1..n and directed, weighted edges times[i] = [u, v, w] (a signal takes w time to go from u to v). A signal starts at node k. Return the time until every node has received it, or -1 if some node never does.
Input[[2,1,1],[2,3,1],[3,4,1]], n=4, k=2Output2
Input[[1,2,1]], n=2, k=1Output1
Input[[1,2,1]], n=2, k=2Output-1

1 ≤ k ≤ n ≤ 100  ·  1 ≤ times.length ≤ 6000  ·  0 ≤ w ≤ 100  ·  u ≠ v, no duplicate (u, v)

Try it yourself

Java
class Solution {
    public int networkDelayTime(int[][] times, int n, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The answer is the largest shortest-path distance from k. Weights are non-negative, so Dijkstra applies: the closest unsettled node can never be improved later.
PatternShortest Paths

Instinct Weighted edges plus "minimum cost, time or effort to reach" - grab a min-heap and always expand the cheapest unsettled node next (Dijkstra).

Memory hack Pop the cheapest, skip the stale, relax the rest - Dijkstra is a ripple in a pond that touches near shores before far ones.

Open the Shortest Paths guide →

Approaches

Brute ForceFloyd–Warshall (All Pairs)

Time O(n3)Space O(n2)

Compute shortest paths between every pair: for each intermediate node m, allow paths through it via d[i][j] = min(d[i][j], d[i][m] + d[m][j]). Then read row k. Use INF = MAX/2 so INF + INF cannot overflow.

Java
public int networkDelayTime(int[][] times, int n, int k) {
    final int INF = Integer.MAX_VALUE / 2;
    int[][] d = new int[n + 1][n + 1];
    for (int[] row : d) Arrays.fill(row, INF);
    for (int i = 1; i <= n; i++) d[i][i] = 0;
    for (int[] t : times) d[t[0]][t[1]] = t[2];
    for (int m = 1; m <= n; m++)
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
                d[i][j] = Math.min(d[i][j], d[i][m] + d[m][j]);
    int ans = 0;
    for (int j = 1; j <= n; j++) ans = Math.max(ans, d[k][j]);
    return ans >= INF ? -1 : ans;
}

Dead simple, but solves an all-pairs problem when we need one source.

At a glance

LevelApproachTimeSpace
Brute ForceFloyd–Warshall (All Pairs)O(n3)O(n2)
BetterBellman–Ford (Relax All Edges)O(n · E)O(n)
OptimalDijkstra with a Min-HeapO(n + E log E)O(n + E)
Common pitfalls
  • Returning the sum of edge times instead of the max shortest distance.
  • Overflow: MAX_VALUE + w wraps negative — guard or use MAX/2.
  • Forgetting 1-indexed nodes — arrays need size n + 1.
Interview tips
  • Clarify: weights ≥ 0? Then Dijkstra; negatives ⇒ Bellman–Ford.
  • Explain the stale-entry skip (lazy deletion) instead of decrease-key.
  • Unreachable node ⇒ its distance stays ∞ ⇒ return -1.
Pattern
Dijkstra → single-source shortest paths on a graph with non-negative weights.
My notes saved in this browser