Know your limits. (Hard version)
This is the hard version of RateLimiter. The only difference between this and the easy version are the constraints. Solving one problem does not guarantee solving the other.
Implement RateLimiter, which tracks a bounded number of events in a rolling time window.
Constructor
RateLimiter(seconds, capacity)
secondsdefines the length of the rolling time window.capacityis the maximum number of events that may exist within the window at any moment.At all times, the RateLimiter should only account for events whose timestamps fall within the most recent
seconds
Methods
add(count, timestamp)
Adds
countnew events occurring at timetimestamp.If adding all
countevents would cause the total number of active events in the window to exceedcapacity, only add as many as possible and discard the remainder.All events added by a single call to
addare considered to occur at the same instant.You may assume calls to
addare made with non-decreasing timestamps.Calls to
addshould not return anything.
check()
- Returns the number of events currently within the active time window.
Notes
Events expire automatically once they fall outside the time window.
The implementation should correctly handle multiple additions at the same timestamp.
No assumptions are made about how events are stored internally.
Constraints
-
count,seconds,capacity,timestamp - At most calls will be made to RateLimiter.
timestampfor each event called sequentially will be in non-decreasing order.
Examples
RateLimiter 3 4
add 6 7
checknull
null
4RateLimiter 3 4
add 1 1
add 1 6
checknull
null
null
1RateLimiter 3 4
add 6 7
checknull
null
4