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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 12 views 0 copies

Python code

23 lines
Python 3.9+
from 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

stdout
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

  1. Use a list with an index pointer instead of a deque if you only need counts, but it's less efficient.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.