Number of Recent Calls

EasyDesigndesign

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Design a RecentCounter that tracks how many requests arrived within a sliding time window. - RecentCounter() starts with no requests recorded. - ping(t) records a new request at time t (in milliseconds) and returns how many recorded requests, including this one, happened in the inclusive range [t - 3000, t]. Every call to ping uses a strictly larger t than the previous call. Each ping should run in amortized O(1) time.

Examples

Input: ["RecentCounter","ping","ping","ping","ping","ping"] [[],[5],[2000],[3005],[3006],[9000]]
Output: [null,1,2,3,3,1]
At t=3005 the window [5, 3005] holds 5, 2000 and 3005. At t=3006 the window [6, 3006] drops 5 but gains 3006. At t=9000 only 9000 is inside [6000, 9000].
Input: ["RecentCounter","ping","ping","ping"] [[],[1],[3001],[3002]]
Output: [null,1,2,2]
The window is inclusive on both ends, so at t=3001 the ping at 1 still counts; at t=3002 it has fallen out.

Constraints

  • 1 <= t <= 10^9
  • Each call to `ping` has a strictly larger `t` than the one before.
  • At most 10^4 calls are made to `ping`.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More design problems