Skip to main content

number-of-recent-calls-leetcode-933

Page 1

Number of Recent Calls (LeetCode 933): A Queue That Forgets the Past Implement RecentCounter with a method ping(t) that returns how many calls happened in the window [t - 3000, t]. Every t is strictly larger than the previous one.

Idea Because times arrive in increasing order, the calls that fell out of the window are always at the front. A deque is enough: append t at the back, then pop from the front everything smaller than t - 3000. The queue length is the answer. from collections import deque class RecentCounter: def __init__(self): self.calls = deque() def ping(self, t): self.calls.append(t) while self.calls[0] < t - 3000: self.calls.popleft() return len(self.calls)

Complexity Each call enters and leaves the queue at most once, so ping is amortized O(1). Memory is bounded by the number of calls inside one 3000 ms window.

Interview notes Say why the increasing order of t makes a plain queue sufficient: without it you would need a sorted structure or binary search. It is also a natural opening to talk about sliding windows and rate limiting, which interviewers often ask as a follow-up. Disclosure: I work on Linkjob AI. To practice explaining problems like this out loud, try AI help for coding interviews from Linkjob AI.


Turn static files into dynamic content formats.

Create a flipbook