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
- 38 lines of Java from the credited upstream file 2747.java.
- 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.
1class Solution {2 public int[] countServers(int n, int[][] logs, int x, int[] queries) {3 int[] ans = new int[queries.length];4 int[] count = new int[n + 1];5 6 Arrays.sort(logs, Comparator.comparingInt(log -> log[1]));7 8 int i = 0;9 int j = 0;10 int servers = 0;11 12 13 for (IndexedQuery indexedQuery : getIndexedQueries(queries)) {14 final int queryIndex = indexedQuery.queryIndex;15 final int query = indexedQuery.query;16 for (; j < logs.length && logs[j][1] <= query; ++j)17 if (++count[logs[j][0]] == 1)18 ++servers;19 for (; i < logs.length && logs[i][1] < query - x; ++i)20 if (--count[logs[i][0]] == 0)21 --servers;22 ans[queryIndex] = n - servers;23 }24 25 return ans;26 }27 28 private record IndexedQuery(int queryIndex, int query){};29 30 private IndexedQuery[] getIndexedQueries(int[] queries) {31 IndexedQuery[] indexedQueries = new IndexedQuery[queries.length];32 for (int i = 0; i < queries.length; ++i)33 indexedQueries[i] = new IndexedQuery(i, queries[i]);34 Arrays.sort(indexedQueries, Comparator.comparingInt(IndexedQuery::query));35 return indexedQueries;36 }37}38