#743 Network Delay Time
the problem
In plain words
A signal starts at node k in a directed, weighted network of n nodes (labelled 1..n). times[i] = [u, v, w] means it takes w time to travel from u to v. Return how long until every node has the signal, or -1 if some node never gets it.
in times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
out 2
Node 4 is the last to hear it: 2→3→4 takes 2.
in times = [[1,2,1]], n = 2, k = 1
out 1
in times = [[1,2,1]], n = 2, k = 2
out -1
From node 2 the signal can't reach node 1.
- 1 ≤ k ≤ n ≤ 100
- 1 ≤ times.length ≤ 6000
- 0 ≤ w ≤ 100
- All (u, v) pairs are unique
your turn
Try it before you peek
Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.
Solve it in the browser
LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.
Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.
Marking the problem solved, or opening every hint, also shows it.
the aha
Key insight
patternDijkstra
Every node hears the signal at its shortest-path distance from k. The answer is the largest of those distances — so run single-source shortest paths and take the max.
solutions
From brute force to optimal
Relax every edge up to n − 1 times, then take the max distance.
- dist[k] = 0, everything else ∞.
- Repeat n − 1 times: relax all edges (stop early if nothing changes).
- Any ∞ → -1, else return the max.
n − 1 rounds over all E edges.
Only the dist array; the edge list is the input.
class Solution { public int networkDelayTime(int[][] times, int n, int k) { int[] dist = new int[n + 1]; Arrays.fill(dist, Integer.MAX_VALUE); dist[k] = 0; for (int round = 1; round <= n - 1; round++) { // n − 1 rounds are always enough boolean changed = false; for (int[] t : times) { int u = t[0], v = t[1], w = t[2]; if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) { dist[v] = dist[u] + w; changed = true; } } if (!changed) break; } int worst = 0; for (int v = 1; v <= n; v++) { if (dist[v] == Integer.MAX_VALUE) return -1; worst = Math.max(worst, dist[v]); } return worst; }}Weights are non-negative, so poll the closest node each time; its distance is final.
- Build an adjacency list (nodes are 1-indexed → size n + 1).
- Push {0, k}. Poll the smallest; skip stale entries.
- Relax outgoing edges, pushing improved distances.
- Return max(dist[1..n]), or -1 if any node is still ∞.
Each edge can push once; each push/poll is O(log E) = O(log n).
Adjacency list plus up to E heap entries.
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<>()); // nodes are 1..n for (int[] t : times) adj.get(t[0]).add(new int[] {t[1], t[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.offer(new int[] {0, k}); while (!pq.isEmpty()) { int[] top = pq.poll(); int d = top[0], u = top[1]; if (d > dist[u]) continue; for (int[] next : adj.get(u)) { int v = next[0], w = next[1]; if (d + w < dist[v]) { dist[v] = d + w; pq.offer(new int[] {dist[v], v}); } } } int worst = 0; for (int v = 1; v <= n; v++) { if (dist[v] == Integer.MAX_VALUE) return -1; // someone never hears the signal worst = Math.max(worst, dist[v]); } return worst; }}Dry run (0-indexed nodes)
in the room
How to say it in the interview
talk track
- Restate: "time for everyone to hear = the farthest node's shortest distance."
- Check weights: non-negative → Dijkstra. Mention Bellman–Ford if they ask about negative times.
- Call out the 1-indexing and the unreachable case before coding.
traps
- Returning the sum of distances instead of the max.
- Allocating
nslots for 1-indexed nodes — you needn + 1.
what they ask next
Follow-ups
What if n were tiny but the graph dense?
The O(n²) array Dijkstra avoids heap overhead and is optimal for E ≈ n².
Return the actual slowest route?
Keep parent[v] on every improvement, find the farthest node, and walk back.
before you submit
Edge cases to test
- Some node is never reached → -1 (check every dist, not only the maximum).
- Zero-weight edges (w can be 0) — fine for Dijkstra.
- The direct edge is slower than a longer route: 1→2 costs 5, but 1→3→2 costs 2.
- k has no outgoing edges and n > 1 → -1.
practise next
Similar problems
- #1514Path with Maximum ProbabilityMediumin Shortest Paths
- #787Cheapest Flights Within K StopsMediumin Shortest Paths
- #994Rotting OrangesMediumin Graphs