Problem Description
Given n servers and a list of logs where each log is of the form [server_id, time], determine for each query time the number of servers that did not receive any requests during the time interval [query - x, query] (inclusive).
Key Insights
- The problem asks us to count servers with zero requests within a moving time window for each query.
- Sorting both the logs (by request time) and the queries (by query time) allows for efficient processing.
- By using a sliding window technique with two pointers over the sorted logs, we can add logs that fall within the window and remove those that fall outside.
- A frequency array (or hash table) is maintained to track the number of requests per server in the current window.
- The difference between the total number of servers and the count of active servers (ones with at least one request) gives the answer for each query.
Space and Time Complexity
Time Complexity: O(L log L + Q log Q + L + Q)
Space Complexity: O(n + L + Q), where L is the number of logs and Q is the number of queries.
Solution
We start by sorting the logs based on their request time and pairing each query with its original index before sorting the queries by their time value. Using a sliding window and two pointers (left and right), we adjust the current window to cover the range [query - x, query]. As we move the pointers, we update a frequency counter for server requests. When a server’s count goes from 0 to 1, we mark it as active; when the count drops back to 0, we mark it as inactive. For each query, the result is calculated by subtracting the number of active servers from the total server count n.