Rate Limiter - Problem
Design and implement a rate limiter that controls the rate of requests using the sliding window algorithm. The rate limiter should allow exactly N requests per time window of W seconds.
Your rate limiter must support:
allow(timestamp)- Returnstrueif the request at the given timestamp is allowed,falseotherwise- The sliding window should continuously move based on the current timestamp
- Only requests within the current time window should be counted
The sliding window algorithm maintains a window that slides forward in time, removing old requests that fall outside the current window before deciding whether to allow new requests.
Input & Output
Example 1 — Basic Rate Limiting
$
Input:
maxRequests = 2, windowSize = 10, requests = [1, 2, 15, 16]
›
Output:
[true, true, true, false]
💡 Note:
First two requests (t=1, t=2) are allowed. At t=15, window [5-15] only contains t=15, so allowed. At t=16, window [6-16] contains t=15 and t=16, reaching limit of 2.
Example 2 — Window Sliding
$
Input:
maxRequests = 3, windowSize = 5, requests = [1, 3, 5, 7, 9]
›
Output:
[true, true, true, true, false]
💡 Note:
Requests at t=1,3,5 fill the limit. At t=7, window [2-7] contains t=3,5,7 (3 requests). At t=9, window [4-9] contains t=5,7 so t=9 would make it 3, but limit is 3, so rejected.
Example 3 — All Requests Allowed
$
Input:
maxRequests = 5, windowSize = 3, requests = [1, 5, 10]
›
Output:
[true, true, true]
💡 Note:
Each request is far enough apart that the sliding window never contains more than 1 request at a time, well under the limit of 5.
Constraints
- 1 ≤ maxRequests ≤ 100
- 1 ≤ windowSize ≤ 1000
- 1 ≤ requests.length ≤ 1000
- 1 ≤ requests[i] ≤ 106
- requests are sorted in non-decreasing order
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code