ping(1), ping(100), ping(3001), ping(3002)[1, 2, 3, 3]Implement RecentCounter. Each ping(t) records a request at time t and returns how many recorded requests fall inside [t - 3000, t], including both endpoints. Timestamps are strictly increasing integer milliseconds.
ping(1), ping(100), ping(3001), ping(3002)[1, 2, 3, 3]At t = 3001, time 1 is exactly 3000 milliseconds old and still counts. At t = 3002, time 1 is outside the window, leaving three recent requests.
ping(1), ping(3002)[1, 1]After a gap longer than 3000 milliseconds, only the new request remains in this example.
Each timestamp is between 1 and 1000000000. Calls arrive in strictly increasing order. The examples show the returned value of each ping, starting with a new counter.
LeetCode 933 ↗ping(1), ping(100), ping(3001), ping(3002) [1, 2, 3, 3]
After n calls, a ping scans n timestamps. Across n calls, these repeated scans take O(n²) total time.
Every request remains stored, so the history uses O(n) space after n calls.
ping(1), ping(100), ping(3001), ping(3002) [1, 2, 3, 3]
Since time only moves forward, an expired request can never matter again. Removing it once avoids scanning the full history on every ping.
Each timestamp enters once and leaves at most once: O(n) total work for n calls. A single ping may remove k expired entries and take O(k) time.
Only the active window is retained. O(n) is a general upper bound. Here, distinct integer timestamps and a fixed 3000 ms window limit the queue to 3001 entries after a ping, so it is also constant space under these fixed constraints.