deque Pops Oldest Pings In A Monotonic Window

A deque as a sliding window evicts timestamps older than the horizon in one amortized pass, so counting pings in the last N seconds stays O(1) per call.

PythonData Integrity

Code

pythonsnippet
18 lines
from collections import deque

class RecentCalls:
    """Counts pings within the last 3000 ms using a monotonic queue."""

    def __init__(self):
        self._times = deque()

    def ping(self, t: int) -> int:
        # evict every timestamp older than the window in one amortized pass
        while self._times and t - self._times[0] > 3000:
            self._times.popleft()
        self._times.append(t)
        return len(self._times)

counter = RecentCalls()
for t in [1, 100, 3001, 3002, 7000]:
    print(f"ping({t}) -> {counter.ping(t)}")

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ping(1) -> 1
ping(100) -> 2
ping(3001) -> 3
ping(3002) -> 3
ping(7000) -> 1

Inside the snippet

All of the logic lives in the class RecentCalls and the functions __init__ and ping.

Repetition is confined to while self._times and t - self._times[0] > 3000 — the rest of the file is straight-line.

Caveats

  • Entirely standard-library — copy it in and it runs.

Putting it to use

The main signature reads def ping(self, t: int) -> int

Look for the ping( prefixes when the file runs; they tie each line to its step.

ping is the public entry point; everything else in the file exists to support it.

Core lines

def ping(self, t: int) -> int:
    # evict every timestamp older than the window in one amortized pass
    while self._times and t - self._times[0] > 3000:
        self._times.popleft()
    self._times.append(t)
    return len(self._times)
def __init__(self):
    self._times = deque()

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `__init__`, `ping` at load time.