InterviewPrepKit

Home / Coding / Arrays & Hashing

Number of Recent Calls

easy Original β†—
Solving tips
  • Recognize a trailing-window count over strictly-increasing timestamps: once a ping ages out it can never re-enter a future window, so it can be discarded forever.
  • Use a FIFO deque: append t, popleft while the front is < t-3000, and return len(window); O(1) amortized per ping (each ping enters and leaves once).
  • The window is inclusive on both ends, so evict with strict < (a ping exactly at t-3000 still counts).
  • Pitfall: use deque.popleft() not list.pop(0), which shifts all elements and reintroduces O(n) per eviction; binary search over the kept list also works but never frees expired entries.

Problem

Design a RecentCounter class that counts requests received in the last 3000 milliseconds.

  • RecentCounter() β€” initializes the counter with no requests recorded.
  • ping(t: int) -> int β€” records a new request at time t (in milliseconds) and returns how many requests occurred in the inclusive window [t - 3000, t], counting this one.

Successive calls to ping use strictly increasing values of t β€” time only moves forward.

Examples

  • Calls: ping(1), ping(100), ping(3001), ping(3002) β†’ Returns: 1, 2, 3, 3 At t=3002 the window is [2, 3002], which excludes the ping at t=1 but keeps 100, 3001, 3002.
  • Calls: ping(1), ping(3002) β†’ Returns: 1, 1 The window at t=3002 is [2, 3002]; the ping at t=1 has aged out, leaving only the new one.
  • Calls: ping(642), ping(1849), ping(4921) β†’ Returns: 1, 2, 1 At t=4921 the window is [1921, 4921]: both 642 and 1849 fall before 1921, so only the new ping counts.

Constraints

  • 1 <= t <= 10^9
  • Each t is strictly larger than the previous one
  • At most 10^4 calls to ping

Total work across all calls should be O(1) amortized per ping (or O(log n) with binary search).

Think about it first

Hint 1 Store every ping time in a list. What does answering a ping cost if you rescan the whole list each time?
Hint 2 Times are strictly increasing. Once a ping falls out of some window, can any *future* window ever include it again?
Hint 3 Keep a queue. On each ping, append `t`, then pop from the front while the front is older than `t - 3000`. The queue's length is the answer β€” each ping is pushed once and popped at most once, so the work is O(1) amortized.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.