File: number-of-recent-calls/solution.py

Date: 2026-06-06

Time: 18:20

number-of-recent-calls/solution.py

Purpose

This file is the complete solution for LeetCode 933 — Number of Recent Calls. It owns both the implementation (RecentCounter) and its test suite. The problem asks you to design a class that counts how many requests have occurred in the last 3000 milliseconds.

Key Components

RecentCounter — A stateful counter backed by a deque (self.q). It exposes a single method:

TestRecentCounter — Five unit tests covering the example case, single-ping, all-within-window, large-gap eviction, and the exact boundary at 3000ms.

Patterns

Sliding window via deque: This is the textbook approach. Because timestamps arrive in strictly increasing order, stale entries are always at the front. A deque gives O(1) append and popleft, making the amortized cost per ping O(1) — each timestamp enters the deque once and leaves once across the lifetime of the object.

Self-contained file: Solution and tests live in the same module with if _name == "main_": unittest.main(), matching the repo-wide convention.

Dependencies

Imports: collections.deque (the sliding window data structure) and unittest (test framework).

Imported by: The testsolution.py in this same directory, plus the "Imported By" list in the prompt shows hundreds of other test files — but that list appears to be the full repo's test suite, not specific to this file. The actual direct dependent is number-of-recent-calls/testsolution.py.

Flow

1. _init_ creates an empty deque.

2. Each ping(t) appends t to the right end.

3. A while loop pops from the left as long as self.q[0] < t - 3000. This is safe because t was just appended, so the deque is never empty during the loop.

4. len(self.q) returns the count of timestamps in [t-3000, t].

Invariants

Error Handling

None. The code trusts the LeetCode contract that t is always a valid, strictly increasing integer. No defensive checks, no exceptions — appropriate for a competitive programming solution.

Topics to Explore

Beliefs