Rate limiter over a sliding window
Write a class RateLimiter(limit, window) for an API: each client may make at most limit requests in any window consecutive seconds.
allow(client, t)handles a request fromclientat secondt. If fewer thanlimitof that client's allowed requests fall at times in(t - window, t], it records this one and returnsTrue; otherwise it returnsFalseand records nothing.
So a request at time t - window has already left the window, and rejected requests never count against the client. Each client is limited separately. Times are non-negative integers that never decrease from one call to the next (several requests may share a second), and limit and window are at least 1. allow must take O(1) amortized time.
The tests call the provided run_limiter(limit, window, requests): it builds the limiter, sends each [client, t] in order and returns the list of answers.
Besides the tests, one large input (10,200 requests, limit 2,000) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.
Examples
run_limiter(2, 10, [["ana",1],["ana",2],["ana",3],["ana",11],["ana",12],["ana",13]])→[true,true,false,true,true,false]run_limiter(1, 5, [["ana",0],["bo",0],["ana",4],["ana",5],["bo",3],["bo",5]])→[true,true,false,true,false,true]run_limiter(3, 4, [["x",0],["x",0],["x",0],["x",0],["x",3],["x",4],["x",4],["x",4],["x",4]])→[true,true,true,false,false,true,true,true,false]