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 minimum 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.

Input & Output

Example 1 — Basic Network
$ Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2
💡 Note: From node 2: reaches node 1 in time 1, node 3 in time 1, and node 4 in time 2. All nodes receive the signal by time 2.
Example 2 — Unreachable Node
$ Input: times = [[1,2,1]], n = 2, k = 2
Output: -1
💡 Note: Starting from node 2, we cannot reach node 1 (edge only goes from 1→2). Return -1.
Example 3 — Single Node
$ Input: times = [], n = 1, k = 1
Output: 0
💡 Note: Only one node exists and it's the source. Signal reaches immediately at time 0.

Constraints

  • 1 ≤ k ≤ n ≤ 100
  • 1 ≤ times.length ≤ 6000
  • times[i].length == 3
  • 1 ≤ ui, vi ≤ n
  • ui ≠ vi
  • 0 ≤ wi ≤ 100
  • All the pairs (ui, vi) are unique

Visualization

Tap to expand
Network Delay Time - Dijkstra's Algorithm INPUT Directed Weighted Graph 2 k=source 1 3 4 1 --> 1 3 --> 1 4 --> 1 times = [[2,1,1],[2,3,1],[3,4,1]] n = 4 (nodes) k = 2 (start node) Edge format: [src, dest, weight] ALGORITHM STEPS 1 Initialize Distances dist[k]=0, others=INF 2 Use Min-Heap (Priority Q) Push (0, k) to heap 3 Process & Relax Edges Update shorter paths 4 Return Max Distance Or -1 if unreachable Distance Table Evolution Node 1 2 3 4 Init INF 0 INF INF v=2 1 0 1 INF v=1 1 0 1 INF v=3 1 0 1 2 Final 1 0 1 2 FINAL RESULT Shortest Paths from Node 2 2 d=0 1 d=1 3 d=1 4 d=2 MAX OUTPUT 2 Max(0,1,1,2) = 2 Key Insight: Dijkstra's algorithm finds shortest paths from source to all nodes using a greedy approach with min-heap. The answer is the maximum of all shortest distances. Time: O(E log V), Space: O(V + E). TutorialsPoint - Network Delay Time | Dijkstra's Algorithm
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
185.0K Views
Medium Frequency
~25 min Avg. Time
4.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen