2039. The Time When the Network Becomes Idle LeetCode Solution

In this guide, you will get 2039. The Time When the Network Becomes Idle LeetCode Solution with the best time and space complexity. The solution to The Time When the Network Becomes Idle problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. The Time When the Network Becomes Idle solution in C++
  4. The Time When the Network Becomes Idle solution in Java
  5. The Time When the Network Becomes Idle solution in Python
  6. Additional Resources
2039. The Time When the Network Becomes Idle LeetCode Solution image

Problem Statement of The Time When the Network Becomes Idle

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:

See also  1681. Minimum Incompatibility LeetCode Solution

If it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server.
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.

Example 1:

Input: edges = [[0,1],[1,2]], patience = [0,2,1]
Output: 8
Explanation:
At (the beginning of) second 0,
– Data server 1 sends its message (denoted 1A) to the master server.
– Data server 2 sends its message (denoted 2A) to the master server.

At second 1,
– Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back.
– Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message.
– Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B).

At second 2,
– The reply 1A arrives at server 1. No more resending will occur from server 1.
– Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back.
– Server 2 resends the message (denoted 2C).

At second 4,
– The reply 2A arrives at server 2. No more resending will occur from server 2.

At second 7, reply 2D arrives at server 2.

See also  1764. Form Array by Concatenating Subarrays of Another Array LeetCode Solution

Starting from the beginning of the second 8, there are no messages passing between servers or arriving at servers.
This is the time when the network becomes idle.

Example 2:

Input: edges = [[0,1],[0,2],[1,2]], patience = [0,10,10]
Output: 3
Explanation: Data servers 1 and 2 receive a reply back at the beginning of second 2.
From the beginning of the second 3, the network becomes idle.

Constraints:

n == patience.length
2 <= n <= 105
patience[0] == 0
1 <= patience[i] <= 105 for 1 <= i < n
1 <= edges.length <= min(105, n * (n – 1) / 2)
edges[i].length == 2
0 <= ui, vi < n
ui != vi
There are no duplicate edges.
Each server can directly or indirectly reach another server.

Complexity Analysis

  • Time Complexity: O(|V| + |E|), where |V| = n and |E| = |\texttt{edges}|
  • Space Complexity: O(|V| + |E|), where |V| = n and |E| = |\texttt{edges}|

2039. The Time When the Network Becomes Idle LeetCode Solution in C++

class Solution {
 public:
  int networkBecomesIdle(vector<vector<int>>& edges, vector<int>& patience) {
    const int n = patience.size();
    int ans = 0;
    vector<vector<int>> graph(n);
    queue<int> q{{0}};
    vector<int> dist(n, INT_MAX);  // dist[i] := the distance between i and 0
    dist[0] = 0;

    for (const vector<int>& edge : edges) {
      const int u = edge[0];
      const int v = edge[1];
      graph[u].push_back(v);
      graph[v].push_back(u);
    }

    while (!q.empty())
      for (int sz = q.size(); sz > 0; --sz) {
        const int u = q.front();
        q.pop();
        for (const int v : graph[u])
          if (dist[v] == INT_MAX) {
            dist[v] = dist[u] + 1;
            q.push(v);
          }
      }

    for (int i = 1; i < n; ++i) {
      const int numResending = (dist[i] * 2 - 1) / patience[i];
      const int lastResendingTime = patience[i] * numResending;
      const int lastArrivingTime = lastResendingTime + dist[i] * 2;
      ans = max(ans, lastArrivingTime);
    }

    return ans + 1;
  }
};
/* code provided by PROGIEZ */

2039. The Time When the Network Becomes Idle LeetCode Solution in Java

class Solution {
  public int networkBecomesIdle(int[][] edges, int[] patience) {
    final int n = patience.length;
    int ans = 0;
    List<Integer>[] graph = new List[n];
    Queue<Integer> q = new ArrayDeque<>(List.of(0));
    int[] dist = new int[n]; // dist[i] := the distance between i and 0
    Arrays.fill(dist, Integer.MAX_VALUE);
    dist[0] = 0;

    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();

    for (int[] edge : edges) {
      final int u = edge[0];
      final int v = edge[1];
      graph[u].add(v);
      graph[v].add(u);
    }

    while (!q.isEmpty())
      for (int sz = q.size(); sz > 0; --sz) {
        final int u = q.poll();
        for (final int v : graph[u])
          if (dist[v] == Integer.MAX_VALUE) {
            dist[v] = dist[u] + 1;
            q.offer(v);
          }
      }

    for (int i = 1; i < n; ++i) {
      final int numResending = (dist[i] * 2 - 1) / patience[i];
      final int lastResendingTime = patience[i] * numResending;
      final int lastArrivingTime = lastResendingTime + dist[i] * 2;
      ans = Math.max(ans, lastArrivingTime);
    }

    return ans + 1;
  }
}
// code provided by PROGIEZ

2039. The Time When the Network Becomes Idle LeetCode Solution in Python

class Solution:
  def networkBecomesIdle(
      self,
      edges: list[list[int]],
      patience: list[int],
  ) -> int:
    n = len(patience)
    ans = 0
    graph = [[] for _ in range(n)]
    q = collections.deque([0])
    dist = [math.inf] * n  # dist[i] := the distance between i and 0
    dist[0] = 0

    for u, v in edges:
      graph[u].append(v)
      graph[v].append(u)

    while q:
      for _ in range(len(q)):
        u = q.popleft()
        for v in graph[u]:
          if dist[v] == math.inf:
            dist[v] = dist[u] + 1
            q.append(v)

    for i in range(1, n):
      numResending = (dist[i] * 2 - 1) // patience[i]
      lastResendingTime = patience[i] * numResending
      lastArrivingTime = lastResendingTime + dist[i] * 2
      ans = max(ans, lastArrivingTime)

    return ans + 1
# code by PROGIEZ

Additional Resources

See also  2879. Display the First Three Rows LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.