#2747

Count Zero Request Servers

Medium
ArrayHash TableSliding WindowSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n * m)
O(n log n + m)
Space
O(m)
O(n)
💡

Intuition

Time O(n log n + m)Space O(n)

By sorting the logs and using a two-pointer technique, we can efficiently determine which servers were active during the query intervals without needing to check each log for every query.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the logs based on the time of requests.
  2. 2Step 2: For each query, determine the time interval [queries[i] - x, queries[i]].
  3. 3Step 3: Use a pointer to traverse the sorted logs and track active servers in a set.
  4. 4Step 4: Count the number of unique servers that received requests in the interval.
  5. 5Step 5: Calculate the number of servers that did not receive requests by subtracting the count from n.
solution.py14 lines
1def countZeroRequestServers(n, logs, x, queries):
2    logs.sort(key=lambda log: log[1])
3    results = []
4    for query in queries:
5        start_time = query - x
6        end_time = query
7        active_servers = set()
8        for server_id, time in logs:
9            if time > end_time:
10                break
11            if start_time <= time <= end_time:
12                active_servers.add(server_id)
13        results.append(n - len(active_servers))
14    return results

Complexity note: The sorting step takes O(n log n), and processing each query takes O(n) in the worst case, leading to an overall complexity of O(n log n + m).

  • 1Sorting the logs allows us to efficiently check which servers were active during each query's time interval.
  • 2Using a set to track active servers ensures we only count unique servers, simplifying the counting process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.