Request Quota Tracker with Rolling Time Windows
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests your ability to track request counts per user within a sliding time window using efficient data structures.
Problem Description
Build a request quota system that tracks whether users stay within their allowed request limits over a rolling time period. You'll process a sequence of operations that check if individual requests should be accepted or rejected.
Your function receives:
max_requests: the maximum number of requests a user can make within the time windowwindow_size: the duration of the rolling window in secondsoperations: a list of operation names (all will be"allow_request")arguments: corresponding arguments for each operation
Each allow_request operation provides:
user_id(string): identifier for the user making the requesttimestamp(integer): the time of the request in seconds since epoch
For each allow_request operation, determine whether the request should be allowed based on how many requests that user has made in the time interval [timestamp - window_size, timestamp] (inclusive on both ends).
Important rules:
- Only accepted requests count toward the limit
- Rejected requests do not consume quota
- The time window includes both boundary timestamps
- Each user is tracked independently
Return a list of boolean values, one per operation, indicating whether each request was allowed.
Constraints
0 ≤ max_requests ≤ 10001 ≤ window_size ≤ 100001 ≤ len(operations) ≤ 10000- All operations are
"allow_request" - Timestamps are non-negative integers
- Timestamps for the same user appear in non-decreasing order
user_idis a non-empty string
Examples
Example 1
Input: track_request_quota(2, 5, ['allow_request', 'allow_request', 'allow_request', 'allow_request'], [['user1', 1], ['user1', 2], ['user1', 3], ['user1', 7]])
Output: [True, True, False, True]
Example 2
Input: track_request_quota(3, 60, ['allow_request', 'allow_request', 'allow_request', 'allow_request'], [['alice', 100], ['bob', 100], ['alice', 120], ['alice', 160]])
Output: [True, True, True, True]
Example 3
Input: track_request_quota(1, 10, ['allow_request', 'allow_request', 'allow_request'], [['u', 0], ['u', 0], ['u', 10]])
Output: [True, False, False]
Hints
Hint 1
Think about which data structure efficiently maintains timestamps in chronological order while allowing removal from the front
Hint 2
Only requests that were accepted need to be remembered - rejected requests don't affect future decisions
Hint 3
The window boundaries are inclusive, so a timestamp exactly equal to (current_time - window_size) should still count
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to maintain a log of accepted request timestamps for each user, then efficiently remove outdated entries as new requests arrive.
Algorithm:
- Store a separate deque (double-ended queue) for each user to hold their accepted request timestamps
- For each incoming request at time
T:- Remove all timestamps from the user's log that fall outside the window (strictly less than
T - window_size) - Count the remaining timestamps - these represent accepted requests still within the window
- If the count is below
max_requests, accept the request and addTto the log - Otherwise, reject the request (and don't add it to the log)
- Remove all timestamps from the user's log that fall outside the window (strictly less than
Why this works:
- Since timestamps arrive in non-decreasing order for each user, the deque stays naturally sorted
- Outdated timestamps always appear at the front, making removal efficient with
popleft() - Only accepted requests are logged, so rejected requests never interfere with future quota calculations
- The window boundaries are inclusive (
[T - window_size, T]), so we only remove timestamps strictly less than the cutoff
Key decision: We only log accepted requests. If we logged rejections too, a user making rapid requests would lock themselves out even after the window expires.
Complexity
- Time: O(N) overall, where N is the total number of operations. Each timestamp is added to a deque once and removed once. Individual operations may take O(max_requests) in the worst case when evicting many old entries, but this is amortized O(1) per request.
- Space: O(U × max_requests), where U is the number of unique users. Each user's log contains at most
max_requeststimestamps.
Solution Code
from collections import defaultdict, deque
from typing import List
def track_request_quota(max_requests: int, window_size: int, operations: List[str], arguments: List[List]) -> List[bool]:
user_logs = defaultdict(deque)
results = []
for operation, args in zip(operations, arguments):
if operation != "allow_request":
raise ValueError("unsupported operation")
user_id, timestamp = args
log = user_logs[user_id]
# Remove timestamps outside the current window
# Window is [timestamp - window_size, timestamp], so remove entries < timestamp - window_size
cutoff = timestamp - window_size
while log and log[0] < cutoff:
log.popleft()
# Check if request can be accepted
if len(log) < max_requests:
log.append(timestamp)
results.append(True)
else:
results.append(False)
return results