Count Zero Request Servers — LeetCode 2747 Python Solution

MediumArrayHash TableSortingSliding Window
Problem
#2747
Reading time
4 min

The 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.

Example

Input
n = 3, logs = [[1,3],[2,6],[1,5]], x = 5, queries = [10,11]
Output
[1,2]
Explanation
For queries[0]: The servers with ids 1 and 2 get requests in the duration of [5, 10]. Hence, only server 3 gets zero requests.

Python solution

Python
class Solution:
    def countServers(
        self, n: int, logs: List[List[int]], x: int, queries: List[int]
    ) -> List[int]:
        cnt = Counter()
        logs.sort(key=lambda x: x[1])
        ans = [0] * len(queries)
        j = k = 0
        for r, i in sorted(zip(queries, count())):
            l = r - x
            while k < len(logs) and logs[k][1] <= r:
                cnt[logs[k][0]] += 1
                k += 1
            while j < len(logs) and logs[j][1] < l:
                cnt[logs[j][0]] -= 1
                if cnt[logs[j][0]] == 0:
                    cnt.pop(logs[j][0])
                j += 1
            ans[i] = n - len(cnt)
        return ans

Complexity

MeasureComplexity
TimeO(l \times \log l + m \times \log m + n)
SpaceO(l + m) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2747. Count Zero Request Servers is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2747. Count Zero Request Servers?
LeetCode 2747. Count Zero Request Servers is rated Medium on LeetCode.
What is the time complexity of LeetCode 2747. Count Zero Request Servers?
The Python solution on this page runs in O(l \times \log l + m \times \log m + n).
What is the space complexity of LeetCode 2747. Count Zero Request Servers?
The Python solution on this page uses O(l + m) auxiliary space.
What topics does LeetCode 2747. Count Zero Request Servers cover?
LeetCode 2747. Count Zero Request Servers is tagged Array, Hash Table, Sorting and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview