Skip to main content
Back to problems
#2039
Medium Algorithms

The time when the network becomes idle

Array Breadth-First Search Graph Theory
55.3% acceptance
Feb 25, 2026
742
77
There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n. All servers are connected, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels. The server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally, so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through. At the beginning of second 0, each data server sends its message to be processed. Starting from second 1, at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server: If it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s). Otherwise, no more resending will occur from this server. The network becomes idle when there are no messages passing between servers or arriving at servers. Return the earliest second starting from which the network becomes idle.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn network_becomes_idle(edges: Vec<Vec<i32>>, patience: Vec<i32>) -> i32 {
    let n = patience.len();
    let mut graph = vec![vec![]; n];
    for e in &edges {
      let (u, v) = (e[0] as usize, e[1] as usize);
      graph[u].push(v);
      graph[v].push(u);
    }

    let mut dist = vec![i64::MAX; n];
    dist[0] = 0;
    let mut queue = std::collections::VecDeque::new();
    queue.push_back(0usize);
    while let Some(u) = queue.pop_front() {
      for &v in &graph[u] {
        if dist[v] == i64::MAX {
          dist[v] = dist[u] + 1;
          queue.push_back(v);
        }
      }
    }

    let mut ans = 0i64;
    for i in 1..n {
      let d = dist[i];
      let p = patience[i] as i64;
      let round_trip = 2 * d;
      // last resend time = floor((round_trip - 1) / p) * p
      let last_send = ((round_trip - 1) / p) * p;
      let last_arrival = last_send + round_trip;
      ans = ans.max(last_arrival + 1);
    }
    ans as i32
  }
}