[LeetCode] Count Zero Request Servers

2747. Count Zero Request Servers

You are given an integer n denoting the total number of servers and a 2D 0-indexed integer array logs, where logs[i] = [server_id, time] denotes that the server with id server_id received a request at time time.

You are also given an integer x and a 0-indexed integer array queries.

Return a 0-indexed integer array arr of length queries.length where arr[i] represents the number of servers that did not receive any requests during the time interval [queries[i] - x, queries[i]].

Note that the time intervals are inclusive.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
vector<int> countServers(int n, vector<vector<int>>& logs, int x, vector<int>& queries) {
vector<pair<int, int>> SQ;
for(int i = 0; i < queries.size(); i++) SQ.push_back({queries[i], i});
sort(begin(SQ), end(SQ));
unordered_map<int, int> freq;
unordered_map<int, vector<int>> mp;
for(auto log : logs) mp[log[1]].push_back(log[0]);
vector<int> res(queries.size());
set<int> times;
for(auto [k,v] : mp) times.insert(k), times.insert(k + x + 1);
for(auto q : queries) times.insert(q);
int j = 0;
for(auto i : times) {
if(j == queries.size()) break;
for(auto s : mp[i]) freq[s] += 1;
for(auto s : mp[i-x-1]) if(--freq[s] == 0) freq.erase(s);
if(i == SQ[j].first) {
res[SQ[j].second] = n - freq.size();
j += 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/25/PS/LeetCode/count-zero-request-servers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.