Approach
Sorting and greedy selection
For Count Zero Request Servers, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 46 lines of C++ from the credited upstream file 2747.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct IndexedQuery {2 int queryIndex;3 int query;4};5 6class Solution {7 public:8 vector<int> countServers(int n, vector<vector<int>>& logs, int x,9 vector<int>& queries) {10 vector<int> ans(queries.size());11 vector<int> count(n + 1);12 13 ranges::sort(logs, ranges::less{},14 [](const vector<int>& log) { return log[1]; });15 16 int i = 0;17 int j = 0;18 int servers = 0;19 20 21 for (const auto& [queryIndex, query] : getIndexedQueries(queries)) {22 for (; j < logs.size() && logs[j][1] <= query; ++j)23 if (++count[logs[j][0]] == 1)24 ++servers;25 for (; i < logs.size() && logs[i][1] < query - x; ++i)26 if (--count[logs[i][0]] == 0)27 --servers;28 ans[queryIndex] = n - servers;29 }30 31 return ans;32 }33 34 private:35 vector<IndexedQuery> getIndexedQueries(const vector<int>& queries) {36 vector<IndexedQuery> indexedQueries;37 for (int i = 0; i < queries.size(); ++i)38 indexedQueries.push_back({i, queries[i]});39 ranges::sort(indexedQueries,40 [](const IndexedQuery& a, const IndexedQuery& b) {41 return a.query < b.query;42 });43 return indexedQueries;44 }45};46