We are in Beta and we are offering 50% off! Use code BETATESTER at checkout.
You can access a significantly larger sample of the platform's content for free by logging in with your Gmail account. Sign in now to explore.

Number of recent calls (Leetcode 933)

Data Structures and Algorithms Easy Seen in real interview

You have a RecentCounter class which counts the number of recent requests within a certain time frame.

Implement the RecentCounter class:

  • RecentCounter() Initializes the counter with zero recent requests.
  • ping(int t) -> int Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request).

Return the number of requests that have happened in the inclusive range [t - 3000, t].

It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.

Examples:

  • Input: [1, 100, 3001, 3002], Output:[1, 2, 3, 3]

  • Input: [1, 3001, 6001], Output: [1, 2, 2]

This is a trivial implementation of a queue: we add an element at the end of the queue, and remove all the irrelevant elements from the beginning of the queue with popleft(). For queues in python we use the deque() class from collections.

from collections import deque
class RecentCounter:
    def __init__(self):
        self.q = deque()

    def ping(self, t: int) -> int:
        self.q.append(t)
        while t - self.q[0] > 3000:
            self.q.popleft()
        return len(self.q)

The time complexity of this solution is \(O(1)\): at max, there will be 3000 elements in the queue since it is gauranteed that each timestamp will be greater than the previous. The space complexiy is also constant, for the same reason.

If we wanted to run it on an example:

counter = RecentCounter()
inputs = [1, 100, 3001, 3002]
print([counter.ping(t) for t in inputs])
## [1, 2, 3, 3]


Topics

Queue, DEQueue
Similar questions

Provide feedback