744. Network Delay Time
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method Explanation
The problem asks for the minimum time for a signal to travel from a source node k to all n nodes in a network. This is a classic single-source shortest path problem on a weighted directed graph. The time for the signal to reach all nodes is determined by the node that receives the signal last. Therefore, the goal is to find the maximum shortest path distance from the source k to any node. If any node is unreachable, it's impossible for all nodes to receive the signal, and we should return -1.
Solution
Network Delay Time in Python
import collections
import heapq
class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
# Adjacency list to represent the graph
# graph[u] = list of tuples (v, w)
adj = collections.defaultdict(list)
for u, v, w in times:
adj[u].append((v, w))
# dist[i] will store the shortest time from k to i
# Using a dictionary for distances for sparse graphs could be an option,
# but with n<=100, a list is fine.
dist = [float('inf')] * (n + 1)
dist[k] = 0
# Min-priority queue to store (distance, node)
pq = [(0, k)]
while pq:
d, u = heapq.heappop(pq)
# If we found a shorter path already, skip
if d > dist[u]:
continue
# Explore neighbors
for v, weight in adj[u]:
# Relaxation step
if dist[u] + weight < dist[v]:
dist[v] = dist[u] + weight
heapq.heappush(pq, (dist[v], v))
# Find the maximum time among all nodes
# We check from index 1 to n (inclusive)
max_time = 0
for i in range(1, n + 1):
# If any node is unreachable, its distance will be infinity
if dist[i] == float('inf'):
return -1
max_time = max(max_time, dist[i])
return max_time
Network Delay Time in Java
class Solution {
public int networkDelayTime(int[][] times, int n, int k) {
// Adjacency list to represent the graph
// adj[u] = list of pairs [v, w]
Map<Integer, List<int[]>> adj = new HashMap<>();
for (int[] time : times) {
adj.computeIfAbsent(time[0], key -> new ArrayList<>()).add(new int[]{time[1], time[2]});
}
// dist[i] will store the shortest time from k to i
int[] dist = new int[n + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[k] = 0;
// Min-priority queue to store {distance, node}
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
pq.offer(new int[]{0, k});
while (!pq.isEmpty()) {
int[] top = pq.poll();
int d = top[0];
int u = top[1];
// If we found a shorter path already, skip
if (d > dist[u]) {
continue;
}
// Explore neighbors
if (adj.containsKey(u)) {
for (int[] edge : adj.get(u)) {
int v = edge[0];
int weight = edge[1];
// Relaxation step
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.offer(new int[]{dist[v], v});
}
}
}
}
// Find the maximum time among all nodes
int maxTime = 0;
for (int i = 1; i <= n; i++) {
// If any node is unreachable, return -1
if (dist[i] == Integer.MAX_VALUE) {
return -1;
}
maxTime = Math.max(maxTime, dist[i]);
}
return maxTime;
}
}
Network Delay Time in C++
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
// Adjacency list to represent the graph
// graph[u] = list of pairs {v, w}
vector<vector<pair<int, int>>> adj(n + 1);
for (const auto& time : times) {
adj[time[0]].push_back({time[1], time[2]});
}
// dist[i] will store the shortest time from k to i
vector<int> dist(n + 1, INT_MAX);
dist[k] = 0;
// Min-priority queue to store {distance, node}
// We use greater<...> to make it a min-heap
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0, k});
while (!pq.empty()) {
int d = pq.top().first;
int u = pq.top().second;
pq.pop();
// If we found a shorter path already, skip
if (d > dist[u]) {
continue;
}
// Explore neighbors
for (const auto& edge : adj[u]) {
int v = edge.first;
int weight = edge.second;
// Relaxation step
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.push({dist[v], v});
}
}
}
// Find the maximum time among all nodes
int max_time = 0;
for (int i = 1; i <= n; ++i) {
// If any node is unreachable, return -1
if (dist[i] == INT_MAX) {
return -1;
}
max_time = max(max_time, dist[i]);
}
return max_time;
}
};
Network Delay Time in TypeScript
class MinPriorityQueue {
private heap: { priority: number; element: number }[];
constructor() {
this.heap = [];
}
enqueue(element: number, priority: number): void {
this.heap.push({ element, priority });
this.bubbleUp();
}
dequeue(): { priority: number; element: number } | null {
if (this.isEmpty()) {
return null;
}
this.swap(0, this.heap.length - 1);
const dequeued = this.heap.pop();
this.bubbleDown();
return dequeued || null;
}
isEmpty(): boolean {
return this.heap.length === 0;
}
private bubbleUp(): void {
let index = this.heap.length - 1;
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if (this.heap[index].priority < this.heap[parentIndex].priority) {
this.swap(index, parentIndex);
index = parentIndex;
} else {
break;
}
}
}
private bubbleDown(): void {
let index = 0;
while (true) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let smallestChildIndex = index;
if (leftChildIndex < this.heap.length && this.heap[leftChildIndex].priority < this.heap[smallestChildIndex].priority) {
smallestChildIndex = leftChildIndex;
}
if (rightChildIndex < this.heap.length && this.heap[rightChildIndex].priority < this.heap[smallestChildIndex].priority) {
smallestChildIndex = rightChildIndex;
}
if (smallestChildIndex !== index) {
this.swap(index, smallestChildIndex);
index = smallestChildIndex;
} else {
break;
}
}
}
private swap(i: number, j: number): void {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
}
function networkDelayTime(times: number[][], n: number, k: number): number {
// Adjacency list to represent the graph
const adj = new Map<number, {to: number, weight: number}[]>();
for (const [u, v, w] of times) {
if (!adj.has(u)) {
adj.set(u, []);
}
adj.get(u)!.push({ to: v, weight: w });
}
// dist[i] will store the shortest time from k to i
const dist = new Array(n + 1).fill(Infinity);
dist[k] = 0;
// Min-priority queue to store {distance, node}
const pq = new MinPriorityQueue();
pq.enqueue(k, 0);
while (!pq.isEmpty()) {
const { priority: d, element: u } = pq.dequeue()!;
// If we found a shorter path already, skip
if (d > dist[u]) {
continue;
}
// Explore neighbors
if (adj.has(u)) {
for (const { to: v, weight } of adj.get(u)!) {
// Relaxation step
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.enqueue(v, dist[v]);
}
}
}
}
// Find the maximum time among all nodes
let maxTime = 0;
for (let i = 1; i <= n; i++) {
if (dist[i] === Infinity) {
return -1;
}
maxTime = Math.max(maxTime, dist[i]);
}
return maxTime;
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.