Number of Recent Calls in Python

The RecentCounter class counts recent requests within a 3000 millisecond time window. When you call ping(t), it returns how many pings occurred in the range [t - 3000, t], including the current ping.

Problem Overview

We need to implement a class that:

  • Maintains a sliding window of 3000 milliseconds
  • Counts pings within this time range
  • Efficiently removes outdated pings

Algorithm Steps

To solve this problem, we follow these steps −

  • Initialize the class with an empty queue to store timestamps
  • For each ping(t) call:
  • Remove timestamps older than t - 3000 from the front of queue
  • Add the current timestamp t to the end of queue
  • Return the current queue size

Implementation

class RecentCounter:
    def __init__(self):
        self.queue = []
    
    def ping(self, t):
        # Remove pings older than t - 3000
        while len(self.queue) and t - self.queue[0] > 3000:
            self.queue.pop(0)
        
        # Add current ping timestamp
        self.queue.append(t)
        
        # Return count of recent pings
        return len(self.queue)

# Test the implementation
counter = RecentCounter()
print(counter.ping(1))     # First ping at t=1
print(counter.ping(100))   # Second ping at t=100
print(counter.ping(3001))  # Third ping at t=3001
print(counter.ping(3002))  # Fourth ping at t=3002
1
2
3
3

How It Works

Let's trace through the example:

  • ping(1): Queue = [1], returns 1
  • ping(100): Queue = [1, 100], returns 2
  • ping(3001): Queue = [1, 100, 3001], returns 3
  • ping(3002): Since 3002 - 1 = 3001 > 3000, remove timestamp 1. Queue = [100, 3001, 3002], returns 3

Optimized Version Using deque

For better performance, use collections.deque since removing from the front of a list is O(n) operation ?

from collections import deque

class RecentCounter:
    def __init__(self):
        self.queue = deque()
    
    def ping(self, t):
        # Remove pings older than t - 3000
        while self.queue and t - self.queue[0] > 3000:
            self.queue.popleft()
        
        # Add current ping timestamp
        self.queue.append(t)
        
        # Return count of recent pings
        return len(self.queue)

# Test the optimized version
counter = RecentCounter()
print(counter.ping(1))
print(counter.ping(100))
print(counter.ping(3001))
print(counter.ping(3002))
1
2
3
3

Time Complexity

Implementation Time Complexity Space Complexity
List with pop(0) O(n) per ping O(n)
Deque with popleft() O(1) amortized O(n)

Conclusion

The RecentCounter uses a sliding window approach with a queue to efficiently count recent pings. The deque implementation provides better performance for frequent removals from the front.

Updated on: 2026-03-25T08:55:08+05:30

518 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements