Algo-Sim › Advanced Graphs
Network Delay Time
Medium · Advanced Graphs · step through it in Java, Python and C++ on your own input
A signal starts at node k and travels along directed, timed edges. How long until every node has it? Dijkstra with a min-heap.
Problem
A network has nodes 1..n and directed edges [u, v, w]: a signal takes w time to travel from u to v. A signal is sent from node k. Return the time when the last node receives it, or -1 if some node never does.
Constraints
- 1 ≤ k ≤ n ≤ 100
- 1 ≤ times.length ≤ 6000
- 0 ≤ w ≤ 100 (no negative weights, so Dijkstra applies)
- No repeated (u, v) pairs
Edge cases to test
- A node that is never reached:
-1 - n = 1:
0 - Several edges between the same pair
Follow-up questions
- Why can’t Dijkstra handle negative edges?
- It finalises a node when popped; a later negative edge could still lower that distance. Use Bellman–Ford instead.
- What is the cost?
- O(E log V) with a binary heap and lazy deletion. For dense graphs the O(V²) array version is faster.
Solution
Java
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[] 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<>(
Comparator.comparingInt((int[] a) -> a[0]).thenComparingInt(a -> a[1]));
pq.offer(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], w = e[1];
if (d + w < dist[v]) {
dist[v] = d + w;
pq.offer(new int[] { dist[v], v });
}
}
}
int max = 0;
for (int i = 1; i <= n; i++) {
if (dist[i] == Integer.MAX_VALUE) return -1;
max = Math.max(max, dist[i]);
}
return max;
}Python
import heapq
def network_delay_time(times, n, k):
adj = [[] for _ in range(n + 1)]
for u, v, w in times:
adj[u].append((v, w))
dist = [float("inf")] * (n + 1)
dist[k] = 0
pq = [(0, k)] # entries are (distance, node)
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue
for v, w in adj[u]:
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(pq, (dist[v], v))
longest = 0
for i in range(1, n + 1):
if dist[i] == float("inf"):
return -1
longest = max(longest, dist[i])
return longestC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int networkDelayTime(vector<vector<int>> ×, int n, int k) {
vector<vector<vector<int>>> adj = {};
for (int i = 0; i <= n; i++)
adj.push_back({});
for (vector<int> &t : times)
adj[t[0]].push_back(vector<int>{t[1], t[2]});
vector<int> dist = vector<int>(n + 1);
fill(dist.begin(), dist.end(), INT_MAX);
dist[k] = 0;
priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;
pq.push(vector<int>{0, k});
while (!pq.empty()) {
vector<int> cur = pq.top();
pq.pop();
int d = cur[0], u = cur[1];
if (d > dist[u])
continue;
for (vector<int> &e : adj[u]) {
int v = e[0], w = e[1];
if (d + w < dist[v]) {
dist[v] = d + w;
pq.push(vector<int>{dist[v], v});
}
}
}
int max = 0;
for (int i = 1; i <= n; i++) {
if (dist[i] == INT_MAX)
return -1;
max = std::max(max, dist[i]);
}
return max;
}
};
More Advanced Graphs problems
- Evaluate Division (Medium)
- Course Schedule II (Medium)
- Alien Dictionary (Hard)
- Redundant Connection (Medium)
- Number of Connected Components (Union-Find) (Medium)
- Accounts Merge (Medium)
- Minimum Spanning Tree (Kruskal) (Medium)
- Minimum Spanning Tree (Prim) (Medium)
- Min Cost to Connect All Points (Medium)
- Cheapest Flights Within K Stops (Medium)
- Bellman-Ford (negative weights) (Medium)
- Find the City (Floyd-Warshall) (Medium)
- Critical Connections in a Network (Hard)
- Articulation Points (Cut Vertices) (Hard)
- Strongly Connected Components (Hard)
- Reconstruct Itinerary (Hard)
- Minimum Height Trees (Medium)