Count Zero Request Servers - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, logs = [[1,3],[2,6],[1,5]], x = 5, queries = [10,11]
Output: [1,2]
💡 Note: For query 10: window [5,10] contains logs [1,5] and [2,6], so servers {1,2} are active, leaving 1 server with zero requests. For query 11: window [6,11] contains only [2,6], so server {2} is active, leaving 2 servers with zero requests.
Example 2 — No Active Servers
$ Input: n = 2, logs = [[1,1],[2,2]], x = 1, queries = [5]
Output: [2]
💡 Note: Query 5 with window [4,5] contains no logs, so all 2 servers have zero requests.
Example 3 — All Servers Active
$ Input: n = 3, logs = [[1,1],[2,2],[3,3]], x = 2, queries = [3]
Output: [0]
💡 Note: Query 3 with window [1,3] contains all logs, so all 3 servers are active, leaving 0 servers with zero requests.

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ logs.length ≤ 105
  • 1 ≤ queries.length ≤ 105
  • logs[i].length == 2
  • 1 ≤ logs[i][0] ≤ n
  • 1 ≤ logs[i][1] ≤ 106
  • 1 ≤ x ≤ 105
  • x + 1 ≤ queries[i] ≤ 106

Visualization

Tap to expand
Count Zero Request Servers INPUT n = 3 servers: S1 S2 S3 logs array: [1, 3] [2, 6] [1, 5] Timeline (x=5): 3 5 6 10 11 queries = [10, 11] 10 11 x = 5 (window size) ALGORITHM STEPS 1 Sort logs by time Sort queries with indices 2 Sliding Window Track active servers in [query-x, query] window 3 Count Active Servers Use HashMap to track request counts per server 4 Calculate Zero Servers n - active_count Query 10: window [5,10] S1@5, S2@6 active Zero servers: 3-2 = 1 Query 11: window [6,11] S2@6 active Zero: 3-1 = 2 Time: O((n+q)log(n+q)) FINAL RESULT Query 10 (window [5,10]): S1 S2 S3 Active: 2 | Zero: 1 Query 11 (window [6,11]): S1 S2 S3 Active: 1 | Zero: 2 = Active = Zero requests Output: [1, 2] OK - Verified! Key Insight: Use sliding window with two pointers on sorted logs. For each query, expand window to include logs within [query-x, query] and shrink to remove expired logs. Track active server count with a HashMap. Zero-request servers = n - (servers with count greater than 0 in window). TutorialsPoint - Count Zero Request Servers | Optimal Solution
Asked in
Amazon 25 Google 18 Microsoft 12 Meta 8
23.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen