Expiring Counter (sliding time window)
Design and implement an expiring counter that counts events in a recent time window.
Requirements
-
You are given a fixed window size
W
in
seconds
when constructing the counter.
-
Support two operations:
-
inc(timestamp, delta=1)
: record
delta
events occurring at integer time
timestamp
(in seconds).
-
get(timestamp) -> int
: return the total number of events recorded in the
inclusive
time range:
[timestamp−W+1,timestamp]
Assumptions / clarifications (state and use in your solution)
-
Timestamps are integer seconds.
-
You may assume calls arrive with
non-decreasing timestamps
(typical for streaming counters). If you choose not to assume this, explain how you would handle out-of-order inputs.
Constraints / goals
-
Aim for efficient time and space usage: roughly
O(1) amortized
per operation and memory proportional to the window.
Follow-up
If inc() can be called up to 1,000,000 times per second, how would you modify the design to reduce memory and CPU overhead (e.g., batching/aggregating within each second)?