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 ProblemInput Network2134111SourceSignal Propagation2134t=0t=1t=1t=2Result2Max TimeSignal reaches: Node 1 at t=1, Node 3 at t=1, Node 4 at t=2Answer: 2 (time when last node receives signal)💡 Key Insight: Find the longest shortest path - that's the network delay time
Understanding the Visualization
1
Input Network
Directed graph with weighted edges and source node
2
Signal Propagation
Signal travels along shortest paths to all reachable nodes
3
Final Result
Time when the last node receives the signal
Key Takeaway
🎯 Key Insight: The network delay is the maximum shortest path distance from source to any node
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