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
- 48 lines of Python from the credited upstream file 2747.py.
- The implementation visibly relies on sequence storage.
- No explicit 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.
1from dataclasses import dataclass2 3 4@dataclass(frozen=True)5class IndexedQuery:6 queryIndex: int7 query: int8 9 def __iter__(self):10 yield self.queryIndex11 yield self.query12 13 14class Solution:15 def countServers(16 self,17 n: int,18 logs: list[list[int]],19 x: int,20 queries: list[int],21 ) -> list[int]:22 ans = [0] * len(queries)23 count = [0] * (n + 1)24 25 logs.sort(key=lambda x: x[1])26 27 i = 028 j = 029 servers = 030 31 32 for queryIndex, query in sorted([IndexedQuery(i, query)33 for i, query in enumerate(queries)],34 key=lambda x: x.query):35 while j < len(logs) and logs[j][1] <= query:36 count[logs[j][0]] += 137 if count[logs[j][0]] == 1:38 servers += 139 j += 140 while i < len(logs) and logs[i][1] < query - x:41 count[logs[i][0]] -= 142 if count[logs[i][0]] == 0:43 servers -= 144 i += 145 ans[queryIndex] = n - servers46 47 return ans48