How to Implement a Recent Counter with a Deque in Python
Implements a RecentCounter class that uses a deque to count ping requests within the last 3000 milliseconds.
Python code
23 linesfrom collections import deque
import time
class RecentCounter:
def __init__(self):
self.hits = deque()
def ping(self, t: int) -> int:
self.hits.append(t)
while self.hits and self.hits[0] < t - 3000:
self.hits.popleft()
return len(self.hits)
if __name__ == "__main__":
counter = RecentCounter()
timestamps = [1, 100, 3001, 3002]
results = []
for ts in timestamps:
results.append(counter.ping(ts))
print(f"Timestamps: {timestamps}")
print(f"Hit counts in last 3000ms: {results}")
Output
Timestamps: [1, 100, 3001, 3002]
Hit counts in last 3000ms: [1, 2, 3, 3]
How it works
The RecentCounter stores timestamps in a deque. Each ping appends the new timestamp and removes from the front any timestamps older than t - 3000 using popleft. Because the deque is sorted by arrival time, this maintains the sliding window efficiently. The length of the deque after cleanup gives the count of hits within the window. Using a deque ensures O(1) append and popleft operations.
Common mistakes
- Using a list and popping from the front with `pop(0)` causes O(n) overhead.
- Forgetting to remove expired timestamps before returning the count.
- Assuming timestamps are always increasing; the code relies on sorted input.
Variations
- Use a list with an index pointer instead of a deque if you only need counts, but it's less efficient.
- Implement a binary search on a list of timestamps for dynamic windows without removal.
Real-world use cases
- Rate limiting APIs by counting requests per client within a sliding time window.
- Tracking recent user actions or events for analytics dashboards.
- Monitoring system health by counting error occurrences in the last few seconds.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.