Data Structures & Algorithms

Graph Theory Interview Questions for Experienced

Deepen your understanding of graph theory for your coding interviews. Our AI-powered guide provides expert insights, advanced problems, and personalized feedback to help you succeed.

Network Delay Time

You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target. We will send a signal from a given node k. Return the time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.

class Solution {   networkDelayTime(times, n, k) {     const dist = new Array(n + 1).fill(Infinity);     dist[k] = 0;
    for (let i = 0; i < n - 1; i++) {       for (const [u, v, w] of times) {         if (dist[u] !== Infinity && dist[u] + w < dist[v]) {           dist[v] = dist[u] + w;         }       }     }
    const maxDist = Math.max(...dist.slice(1));     return maxDist === Infinity ? -1 : maxDist;   } }

This problem can be solved using Dijkstra's algorithm or the Bellman-Ford algorithm. Since the edge weights are non-negative, Dijkstra's would be more efficient. However, the provided solution uses the Bellman-Ford algorithm. It initializes distances to all nodes as infinity, except for the source node k. It then relaxes the edges repeatedly. The maximum distance to any node after n-1 iterations will be the answer. If any distance is still infinity, it means not all nodes are reachable.

Related Algorithm Guides

Explore more algorithm interview guides powered by AI coaching

Bellman Ford Algorithm Interview Questions
AI-powered interview preparation guide
Floyd Warshall Algorithm Interview Questions
AI-powered interview preparation guide
Topological Sort Dfs Interview Questions
AI-powered interview preparation guide
Junior Business Analyst Case Interview Preparation
AI-powered interview preparation guide