Dual-Quota Request Throttle with Sliding Time Window
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate a throttle that enforces a per-user and a per-game quota over a sliding time window, recording a request only when both quotas have room.
Dual-Quota Request Throttle
A service receives a stream of requests, each made by a user against a game and stamped with a time in milliseconds. You must decide, for each request in order, whether to accept or reject it. Two independent quotas apply:
- User quota: a single user may have at most
per_user_capaccepted requests inside the window. - Game quota: a single game may have at most
per_game_capaccepted requests inside the window.
The window
The window has length window_ms. When a request arrives at time t, an earlier accepted request at time s counts toward the quota only if t - s < window_ms. In other words, the window is (t - window_ms, t]. A request made exactly window_ms milliseconds earlier no longer counts.
Decision rule
For the request (user_id, game_id, t):
- Count the accepted requests of that user inside the window.
- Count the accepted requests of that game inside the window.
- Accept the request only if the user count is strictly less than
per_user_capand the game count is strictly less thanper_game_cap. - If accepted, record
tfor both the user and the game. If rejected, record nothing for either. A rejected request never uses up any quota.
Only accepted requests are ever counted. Several requests with the same timestamp each count separately.
Input format
operations: a list of strings. Every entry is"allow".arguments: a list of the same length. The i-th entry is[user_id, game_id, timestamp_ms]for the i-th operation.per_user_cap: the user quota.per_game_cap: the game quota.window_ms: the window length in milliseconds.
If any operation is not "allow", or any argument list does not have exactly three integers, raise ValueError.
Output
Return a list of booleans, one per request in input order. Each is True if the request was accepted and False otherwise.
Constraints
operationsandargumentshave the same length.- Timestamps are non-decreasing across the stream.
- Timestamps, ids, and
window_msare integers.window_ms >= 1. per_user_capandper_game_capare non-negative integers. A cap of0rejects every request.- The number of requests can be large, so aim for roughly linear total time.
Examples
Example 1
Input: throttle_requests(['allow', 'allow', 'allow', 'allow', 'allow'], [[1, 10, 1000], [1, 10, 1001], [2, 10, 1002], [1, 20, 1003], [1, 10, 2000]], 2, 2, 1000)
Output: [True, True, False, False, True]
Example 2
Input: throttle_requests(['allow', 'allow', 'allow'], [[7, 3, 0], [7, 4, 1], [8, 3, 2]], 1, 1, 10)
Output: [True, False, False]
Hints
Hint 1
Only accepted requests matter, so keep a log of accepted timestamps per user and per game. Because time never goes backwards, each log is already sorted.
Hint 2
Before deciding, drop timestamps from the front of both logs that satisfy t - s >= window_ms. A double-ended queue makes this cheap.
Hint 3
Check both quotas before modifying anything. Append the timestamp to both logs only if both have room, otherwise leave both untouched.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep one log of accepted timestamps for every user and one for every game, each stored in a deque. Because timestamps never decrease, every log is sorted with the oldest entry at the front.
For each request at time t:
- Pop entries from the front of the user's deque while
t - front >= window_ms. Do the same for the game's deque. - Whatever remains in each deque is exactly the set of accepted requests in
(t - window_ms, t]. - Accept only if the user deque has fewer than
per_user_capentries and the game deque has fewer thanper_game_capentries. - If accepted, append
tto both deques. If rejected, change nothing.
Why it is correct
- Each deque holds only accepted requests, and since the stream is time-ordered, all stale entries sit at the front. Popping from the front until the oldest entry is inside the window removes exactly the stale ones.
- The decision depends on both counts and is made before any mutation. A request rejected by one quota therefore never consumes capacity in the other. Recording the user entry first and then discovering the game is full would leave a phantom entry that wrongly throttles that user later.
- A cap of 0 makes
len(...) < 0always false, so everything is rejected. Duplicate timestamps are appended separately and each counts. - The strict test
t - s >= window_msfor eviction implements the half-open window, so an entry exactlywindow_msold no longer counts.
Complexity
- Time: amortized O(1) per request, O(R) overall. Each accepted timestamp is appended once to each of two deques and popped at most once from each.
- Space: a user deque never exceeds
per_user_capentries and a game deque never exceedsper_game_cap, so memory is O(U * per_user_cap + G * per_game_cap) for U users and G games seen. In a long-running service you would also delete keys whose deques become empty.
Reference solution
from collections import defaultdict, deque
from typing import List
def throttle_requests(operations: List[str], arguments: List[List[int]],
per_user_cap: int, per_game_cap: int,
window_ms: int) -> List[bool]:
user_log = defaultdict(deque)
game_log = defaultdict(deque)
results = []
for operation, args in zip(operations, arguments):
if operation != "allow" or len(args) != 3:
raise ValueError("Each operation must be 'allow' with [user_id, game_id, timestamp_ms]")
user_id, game_id, t = args
users = user_log[user_id]
games = game_log[game_id]
# Keep only timestamps in (t - window_ms, t].
while users and t - users[0] >= window_ms:
users.popleft()
while games and t - games[0] >= window_ms:
games.popleft()
allowed = len(users) < per_user_cap and len(games) < per_game_cap
if allowed:
users.append(t)
games.append(t)
results.append(allowed)
return results