EasyNo. 0933

Number of Recent Calls — LeetCode 933 Python Solution

Pattern
Stack
Topics
Design, Queue, Data Stream
On a study list
LeetCode 75
Reading time
3 min

The problem

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.

Example

Input
["RecentCounter", "ping", "ping", "ping", "ping"]
Output
[null, 1, 2, 3, 3]
Explanation
RecentCounter recentCounter = new RecentCounter();

Python solution

PythonSolution
class RecentCounter:
    def __init__(self):
        self.q = deque()

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


# Your RecentCounter object will be instantiated and called as such:
# obj = RecentCounter()
# param_1 = obj.ping(t)

Complexity

Time
O(V+E)
Space · auxiliary
O(V)

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 933. Number of Recent Calls is filed here because LeetCode tags it Queue, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 933. Number of Recent Calls?

LeetCode 933. Number of Recent Calls is rated Easy on LeetCode.

What is the time complexity of LeetCode 933. Number of Recent Calls?

The Python solution on this page runs in O(V+E).

What is the space complexity of LeetCode 933. Number of Recent Calls?

The Python solution on this page uses O(V) auxiliary space.

What topics does LeetCode 933. Number of Recent Calls cover?

LeetCode 933. Number of Recent Calls is tagged Design, Queue and Data Stream 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.

Free to download. Check it runs on your machine, then pick a plan.