Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
There are n network nodes labelled 1 to n. You get times, a list of directed edges [u, v, w]: a signal sent from u reaches v after w time units. The signal starts at node k at time 0 and spreads along every edge at once. Return the time at which all nodes have received it, or -1 if some node can never receive it. Limits: n ≤ 100, up to 6000 edges, and 0 ≤ w ≤ 100.
Example: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2 → 2. Nodes 1 and 3 hear it at time 1, and node 4 hears it at time 2.
Start with brute force
Each node hears the signal at the time of its shortest path from k, so the answer is the largest shortest-path distance.
The simplest way to get all those distances is Bellman-Ford: set dist[k] = 0 and every other distance to infinity, then go over every edge and relax it (dist[v] = min(dist[v], dist[u] + w)). Repeat that n − 1 times. It works because a shortest path uses at most n − 1 edges. The cost is O(n · E), which is 600,000 steps here. That's fine for these limits, but it wastes a lot of work, and it falls over once graphs have 10⁵ nodes.
Building the intuition
BFS is the shortest-path tool when every edge costs 1. Here a direct edge of cost 5 can lose to a two-edge path of cost 1 + 1, so "fewest edges" is not "fastest".
Picture water spreading from k through pipes of different lengths. Which node gets wet first? The one at the end of the cheapest edge out of k. Nothing can beat that, because any other route starts with a more expensive edge, and costs never go negative.
Now that node is settled. Its neighbours get new candidate times. Again, the unsettled node with the smallest candidate time is the next to get wet. Any other route to it would go through some other unsettled node, which already costs at least as much.
So the rule is: repeatedly take the unsettled node with the smallest tentative time, and lock it in. Picking "the smallest" over and over is what a min-heap does in O(log size). That's Dijkstra's algorithm.
To keep it simple, don't try to update entries already in the heap. Just push a new (time, node) pair whenever you find a route. A node can end up in the heap several times, but only its first pop is the real one. Later pops are stale, so skip them.
The optimal approach
- Build an adjacency list:
graph[u]holds(v, w)pairs. - Set
dist[i] = -1for every node (meaning not settled) and push(0, k)onto a min-heap. - While the heap isn't empty:
- pop the smallest
(d, u); ifuis already settled, skip it (it's stale); - otherwise set
dist[u] = d, count it as settled, and track the maxd; - push
(d + w, v)for each neighbourvthat isn't settled yet.
- pop the smallest
- If all
nnodes were settled, return the max time. Otherwise return-1.
The subtle detail is that a distance is final when it's popped, not when it's pushed. A node can be pushed with time 5 first and with time 2 later. The heap pops the 2 first, and the 5 is skipped as stale.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
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), nodes are 1..n
for u, v, w in times:
graph[u].append((v, w))
dist = [-1] * (n + 1) # -1 = not settled yet
heap = [(0, k)] # min-heap of (time to reach node, node)
settled = answer = 0
while heap:
d, u = heapq.heappop(heap)
if dist[u] != -1:
continue # stale entry: u was already settled with a smaller time
dist[u] = d # the smallest time in the heap is final (weights are >= 0)
settled += 1
answer = max(answer, d)
for v, w in graph[u]:
if dist[v] == -1:
heapq.heappush(heap, (d + w, v))
# every node must hear the signal; the last one to hear it sets the answer
return answer if settled == n else -1class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
vector<vector<pair<int, int>>> graph(n + 1); // graph[u] = (v, w), nodes are 1..n
for (auto& t : times) graph[t[0]].push_back({t[1], t[2]});
vector<int> dist(n + 1, -1); // -1 = not settled yet
// min-heap of (time to reach node, node)
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> heap;
heap.push({0, k});
int settled = 0, answer = 0;
while (!heap.empty()) {
auto [d, u] = heap.top();
heap.pop();
if (dist[u] != -1) continue; // stale entry: u already settled with a smaller time
dist[u] = d; // smallest time in the heap is final (weights >= 0)
settled++;
answer = max(answer, d);
for (auto [v, w] : graph[u]) {
if (dist[v] == -1) heap.push({d + w, v});
}
}
// every node must hear the signal; the last one to hear it sets the answer
return settled == n ? answer : -1;
}
};class Solution {
public int networkDelayTime(int[][] times, int n, int k) {
List<List<int[]>> graph = new ArrayList<>(); // graph.get(u) = {v, w}, nodes are 1..n
for (int i = 0; i <= n; i++) graph.add(new ArrayList<>());
for (int[] t : times) graph.get(t[0]).add(new int[] { t[1], t[2] });
int[] dist = new int[n + 1];
Arrays.fill(dist, -1); // -1 = not settled yet
// min-heap of {time to reach node, node}
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
heap.add(new int[] { 0, k });
int settled = 0, answer = 0;
while (!heap.isEmpty()) {
int[] top = heap.poll();
int d = top[0], u = top[1];
if (dist[u] != -1) continue; // stale entry: u already settled with a smaller time
dist[u] = d; // smallest time in the heap is final (weights >= 0)
settled++;
answer = Math.max(answer, d);
for (int[] edge : graph.get(u)) {
if (dist[edge[0]] == -1) heap.add(new int[] { d + edge[1], edge[0] });
}
}
// every node must hear the signal; the last one to hear it sets the answer
return settled == n ? answer : -1;
}
}// JavaScript has no built-in heap, so here is a small binary min-heap of [key, value] pairs.
class MinHeap {
constructor() {
this.a = [];
}
get size() {
return this.a.length;
}
push(item) {
const a = this.a;
a.push(item);
let i = a.length - 1;
while (i > 0) { // sift up while the parent is bigger
const p = (i - 1) >> 1;
if (a[p][0] <= a[i][0]) break;
[a[p], a[i]] = [a[i], a[p]];
i = p;
}
}
pop() {
const a = this.a;
const top = a[0];
const last = a.pop();
if (a.length) {
a[0] = last;
let i = 0;
while (true) { // sift down towards the smaller child
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < a.length && a[l][0] < a[m][0]) m = l;
if (r < a.length && a[r][0] < a[m][0]) m = r;
if (m === i) break;
[a[m], a[i]] = [a[i], a[m]];
i = m;
}
}
return top;
}
}
/**
* @param {number[][]} times
* @param {number} n
* @param {number} k
* @return {number}
*/
var networkDelayTime = function (times, n, k) {
const graph = Array.from({ length: n + 1 }, () => []); // graph[u] = [v, w], nodes are 1..n
for (const [u, v, w] of times) graph[u].push([v, w]);
const dist = new Array(n + 1).fill(-1); // -1 = not settled yet
const heap = new MinHeap(); // entries are [time to reach node, node]
heap.push([0, k]);
let settled = 0, answer = 0;
while (heap.size) {
const [d, u] = heap.pop();
if (dist[u] !== -1) continue; // stale entry: u already settled with a smaller time
dist[u] = d; // smallest time in the heap is final (weights >= 0)
settled++;
answer = Math.max(answer, d);
for (const [v, w] of graph[u]) {
if (dist[v] === -1) heap.push([d + w, v]);
}
}
// every node must hear the signal; the last one to hear it sets the answer
return settled === n ? answer : -1;
};Dry run
times = [[1,2,5],[1,3,1],[3,2,1]], n = 3, k = 1
| Pop | Stale? | Settled after | Pushed | Heap after |
|---|---|---|---|---|
| (0, 1) | no | dist[1] = 0 | (5, 2), (1, 3) | (1,3), (5,2) |
| (1, 3) | no | dist[3] = 1 | (2, 2) | (2,2), (5,2) |
| (2, 2) | no | dist[2] = 2 | none | (5,2) |
| (5, 2) | yes, 2 is settled | empty |
All 3 nodes are settled, and the largest time is 2. The direct edge 1 → 2 (cost 5) lost to 1 → 3 → 2 (cost 2).
Complexity
- Time: O(E log E). Every edge pushes at most one entry, and each push or pop costs O(log E). Since E ≤ n², log E ≤ 2 log n, so you'll often see this written as O(E log n).
- Space: O(n + E) for the adjacency list and the heap.
Edge cases and traps
- Using BFS. It returns the path with the fewest edges, not the fastest one. Example: 5 versus 1 + 1.
- Locking in distances on push. A distance is final only when it's popped.
- Not skipping stale entries. Without the skip you re-expand nodes, which is slower and can overwrite correct distances.
- Unreachable nodes. Edges are directed. If node
khas no path to some node, return-1, not the max of the reachable ones. - Off-by-one on labels. Nodes are
1..n, so size arraysn + 1. - Negative weights. Dijkstra breaks with them, though this problem guarantees
w ≥ 0. With negative edges you'd use Bellman-Ford.
Say it in the interview
"Each node hears the signal at its shortest-path time from k, so I need the largest shortest-path distance. The weights are non-negative, so that's Dijkstra. I keep a min-heap of (time, node). When I pop a node for the first time, its time is final, and I push its neighbours with time + w. Later pops of the same node are stale and get skipped. If I settle all n nodes I return the max time, otherwise -1. O(E log E) time, O(n + E) space."
Follow-ups interviewers ask
- "Why does Dijkstra need non-negative weights?" The proof assumes extending a path never makes it cheaper. A negative edge breaks that, so a node you already settled could later get a cheaper route.
- "What if you can use at most K edges?" That's Cheapest Flights Within K Stops. Use Bellman-Ford limited to K + 1 rounds, or run Dijkstra on (node, stops) states.
- "Dense graph?" With E close to n², an array-based Dijkstra (scan for the minimum each round, no heap) is O(n²), which beats O(n² log n). Min Cost to Connect All Points uses the same trick for Prim.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free