#933

Number of Recent Calls

Easy
DesignQueueData StreamQueueSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

In the optimal solution, we use a queue to store the ping times. When a new ping comes in, we remove all pings that are older than 3000 milliseconds from the current ping time. This allows us to efficiently count the recent pings.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a queue to store the ping times.
  2. 2Step 2: For each ping at time t, add t to the queue.
  3. 3Step 3: Remove pings from the front of the queue while they are older than t - 3000.
  4. 4Step 4: The size of the queue now represents the number of recent requests.
solution.py11 lines
1from collections import deque
2
3class RecentCounter:
4    def __init__(self):
5        self.pings = deque()
6
7    def ping(self, t: int) -> int:
8        self.pings.append(t)
9        while self.pings[0] < t - 3000:
10            self.pings.popleft()
11        return len(self.pings)

Complexity note: The time complexity is O(n) for the worst case where all pings are within the range, but each ping is processed in constant time on average due to the queue operations. The space complexity is O(n) because we store all pings in the queue.

  • 1Using a queue allows us to efficiently manage the pings and remove old entries.
  • 2The problem requires us to maintain a sliding window of recent requests.

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