Count Zero Request Servers - Sorting and Sliding Window [JS]
Solution: Sorting and Sliding Window
For each request, think of the request expiry time as request time + x
.
- Sort
queries
in asc order by time. - Sort
logs
in asc order by time. - Go through each query, while maintaining a sliding window of non-expired requests.
a. Expand the right side of the window whilerequest time <= queryTime
b. Move up left side of the window while requests are expired
Keep updatingactiveCount
, whereactiveCount[server_id] = the number of active logs for the given server_id
Keep track of the global count of active servers.
k = number of logs
, m = 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
Post a Comment