Per-User Request Throttle Simulator with Rolling Time Window
Data Structure DesignAuto-graded · 16 test casesLast updated
Replay a list of throttle operations and decide, per user, whether each request fits within k accepted requests in a rolling window of t ms, using inclusive boundary rules.
Per-User Request Throttle
A service limits how often each user may call it. At most k requests from the same user may be accepted within any rolling window of t milliseconds. You are given a recorded sequence of operations to replay, and you must report the outcome of each one.
Input
operations: a list of strings. Each one is either a setup operation or a request operation.- Setup:
"RateLimiter"(the names"__init__"and"init"mean the same thing). - Request:
"allow_request".
- Setup:
arguments: a list of the same length asoperations.arguments[i]holds the arguments foroperations[i].- Setup:
[k, t], the maximum number of accepted requests and the window length in milliseconds. - Request:
[user_id, timestamp], a string user identifier and an integer timestamp in milliseconds.
- Setup:
Behavior
- A setup operation configures
kandtand discards every previously stored request, for all users. Its result isNone. - For a request
[user_id, timestamp], look only at the accepted requests previously made by that same user. Users never affect each other.- An earlier accepted request at time
scounts toward the current window whens >= timestamp - t. The window is closed at both ends:[timestamp - t, timestamp]. - If fewer than
kearlier accepted requests count, the new request is accepted. The result isTrue, and the request is remembered for later calls. - Otherwise the request is rejected. The result is
False, and the request is not remembered, so rejected requests never use up capacity.
- An earlier accepted request at time
- Any other operation name is invalid, and the function should raise
ValueError.
Output
Return a list with one entry per operation, in order. Use None for setup operations and True or False for request operations.
Constraints
operationsandargumentshave the same length, and the first operation is a setup operation.kandtare positive integers.- Every
timestampis a positive integer. - Within the calls for a given user, timestamps are strictly increasing.
- Old entries should be discarded efficiently, so the memory kept for each user stays bounded by
k.
Examples
Example 1
Input: simulate_request_throttle(['RateLimiter', 'allow_request', 'allow_request', 'allow_request', 'allow_request'], [[2, 1000], ['user1', 100], ['user1', 500], ['user1', 1200], ['user1', 1300]])
Output: [None, True, True, True, False]
Example 2
Input: simulate_request_throttle(['RateLimiter', 'allow_request', 'allow_request', 'allow_request'], [[1, 100], ['u', 100], ['u', 200], ['u', 201]])
Output: [None, True, False, True]
Hints
Hint 1
Keep a separate queue of accepted timestamps for each user, for example in a dictionary from user id to a deque.
Hint 2
Because timestamps only grow, the entries that have expired are always at the front of the queue. Pop from the front while the oldest entry is strictly less than timestamp - t.
Hint 3
Check the boundary carefully: an entry exactly t milliseconds old still counts. Only append the timestamp when the request is accepted, never when it is rejected.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep a dictionary that maps each user to a deque of the timestamps of that user's accepted requests, oldest on the left. Replay the operations in order:
- On a setup operation, store
kandt, reset the dictionary, and outputNone. - On a request at
timestamp:- Compute
cutoff = timestamp - t. - Pop from the left of the user's deque while the front value is
< cutoff. These entries are outside the closed window[timestamp - t, timestamp]. - If the deque has fewer than
kentries, appendtimestampand outputTrue. - Otherwise output
Falseand store nothing.
- Compute
Why it is correct
- Sorted deque. Timestamps for a user are strictly increasing and we append in arrival order, so the deque is sorted. The expired entries therefore form a prefix, and popping from the front removes exactly them.
- Correct count. After eviction, the deque length equals the number of accepted requests in the current window. Accepting only when this count is below
kmeans no window ever holds more thankaccepted requests. - Boundary rule. An entry is evicted only when it is strictly less than
timestamp - t. An entry exactlytms old stays and counts, matching the closed window. - Rejected requests are not stored. If they were, a client that keeps retrying would keep its own window full and never be let in again.
- Independence. Each user has a separate deque, so users do not interact.
Complexity
- Time: amortized O(1) per request, because each timestamp is appended once and popped at most once. A single call can cost O(k) in the worst case.
- Space: O(U * k), where
Uis the number of distinct users, since each deque holds at mostktimestamps.
Reference solution
from collections import defaultdict, deque
from typing import List, Optional
def simulate_request_throttle(operations: List[str], arguments: List[List]) -> List[Optional[bool]]:
capacity = window = None
accepted = defaultdict(deque)
results = []
for operation, args in zip(operations, arguments):
if operation in ("RateLimiter", "__init__", "init"):
capacity, window = args
accepted = defaultdict(deque)
results.append(None)
elif operation == "allow_request":
user_id, timestamp = args
queue = accepted[user_id]
cutoff = timestamp - window
# Drop entries that are strictly older than the window start.
while queue and queue[0] < cutoff:
queue.popleft()
if len(queue) < capacity:
queue.append(timestamp)
results.append(True)
else:
results.append(False)
else:
raise ValueError(f"Unknown operation: {operation}")
return results