Sliding window · Medium
A per-account rate limiter accepts at most limit requests in a trailing window. Rejected requests must not consume future allowance.
Return one acceptance decision per arrival.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ times:integer[], window:integer, limit:integer }. times is nondecreasing and may contain ties
What each field means
times— arrival timestamps in nondecreasing order; equal timestamps are allowed.window— how long an accepted request counts against the limit.limit— maximum number of accepted requests in that time window.
Output
Return value and rules
- Return one boolean per arrival:
truefor accepted andfalsefor rejected. - At time
t, count earlier accepted requests with timestamp strictly greater thant - window. - Accept only when that count is below
limit. Rejected requests never count against later arrivals.
Constraints
- 0 <= times.length <= 100000; timestamps in [0,1000000000]
- 1 <= window <= 1000000000; 0 <= limit <= 100000
- An arrival exactly window units old is expired.
Examples
Example 1
{
"limit": 2,
"times": [
0,
1,
2,
5
],
"window": 5
}Returns
[
true,
true,
false,
true
]Example 2
{
"limit": 1,
"times": [],
"window": 1
}Returns
[]Required complexity
O(n) time and O(n) space