RateLimiter 3 4
add 6 7
checknull
null
4add() only adds 4 elements out of the 6 because the RateLimiter has a capacity of 4.
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.
RateLimiter(seconds, capacity)seconds defines the length of the rolling time window.
capacity is the maximum number of events that may exist within the window at any moment.
The latest timestamp passed to add is the current time. An event is active exactly while its timestamp is in (current_time - seconds, current_time]. An event at current_time - seconds has expired.
add(count, timestamp)Adds count new events occurring at time timestamp.
If adding all count events would cause the total number of active events in the window to exceed capacity, only add as many as possible and discard the remainder.
All events added by a single call to add are considered to occur at the same instant.
You may assume calls to add are made with non-decreasing timestamps.
Calls to add should not return anything.
check()check() does not advance time.Events expire automatically once they fall outside the time window.
The implementation should correctly handle multiple additions at the same timestamp.
How you store events internally is up to you.
count, seconds, capacity, timestamp timestamp for each event called sequentially will be in non-decreasing order.RateLimiter 3 4
add 6 7
checknull
null
4add() only adds 4 elements out of the 6 because the RateLimiter has a capacity of 4.
RateLimiter 3 4
add 1 1
add 1 6
checknull
null
null
1The first call to add() adds an element at timestamp 1, and the second call to add() adds an element at timestamp 6. Because the first event now falls outside the time window, it is discarded.
RateLimiter 3 4
add 6 7
checknull
null
4