Count Zero Request Servers - Sorting and Sliding Window [JS]

Description 

Solution: Sorting and Sliding Window

For each request, think of the request expiry time as request time + x.

  1. Sort queries in asc order by time.
  2. Sort logs in asc order by time.
  3. Go through each query, while maintaining a sliding window of non-expired requests.
    a. Expand the right side of the window while request time <= queryTime
    b. Move up left side of the window while requests are expired
    Keep updating activeCount, where activeCount[server_id] = the number of active logs for the given server_id
    Keep track of the global count of active servers.

k = number of logsm = number of queries
Time Complexity: O(m log(m) + k log(k) + n)
Space Complexity: O(n + m)

var countServers = function(n, logs, x, queries) {
  queries = queries.map((time, idx) => [time, idx]).sort((a, b) => a[0] - b[0]);
  logs.sort((a, b) => a[1] - b[1]);
  let activeCount = Array(n + 1).fill(0), activeServers = 0, j = 0, i = 0, res = Array(queries.length);
  for (let [queryTime, queryIndex] of queries) {
    // expand the right side of the window while request time <= queryTime
    while (j < logs.length && logs[j][1] <= queryTime) {
      let [server_id] = logs[j];
      if (++activeCount[server_id] === 1) activeServers++;
      j++;
    }
    // move up left pointer of window while requests are expired
    while (i < j && logs[i][1] + x < queryTime) {
      let [server_id] = logs[i];
      if (--activeCount[server_id] === 0) activeServers--;
      i++;
    }
    res[queryIndex] = n - activeServers;
  }
  return res;
};

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]