Sliding-Window Throttle with Global, Per-User and Per-Experience Caps
Data Structure DesignAuto-graded · 21 test casesLast updated
Simulate a sliding-window throttle with a global cap and a combined per-user and per-experience cap, where the combined check must be all-or-nothing.
You are building a throttle for an API and must simulate how it responds to a sequence of calls. A single throttle instance handles every call, in order.
Operations
Two kinds of calls are supported:
"allow"with arguments[timestamp]. It is judged only against the global limit: at mostglobal_limitaccepted calls in any sliding window."allow_multi"with arguments[user_id, experience, timestamp]. It is judged against two independent limits:- at most
user_limitaccepted calls peruser_idin any sliding window, and - at most
experience_limitaccepted calls perexperiencevalue in any sliding window.
- at most
The call is accepted only if both limits have room. If it is accepted, it counts toward both the user's tally and the experience's tally. If it is rejected, it counts toward neither. A call refused because of one limit must not consume capacity from the other.
Sliding window
The window has length window milliseconds. For a call at time t, the relevant earlier calls are the accepted ones whose timestamps fall in the closed range [t - window + 1, t]. A call is accepted if the number of such calls for the relevant key is strictly less than the limit.
Rejected calls are never counted. Several accepted calls may share the same timestamp, and all of them count.
Independence of state
"allow"calls and"allow_multi"calls keep separate histories. An"allow"call never affects an"allow_multi"call, and the reverse.- Each distinct
user_idhas its own history, and each distinctexperiencehas its own history. The same user in different experiences shares one user history, and the same experience across different users shares one experience history.
Task
Implement simulate_throttle(operations, arguments, global_limit, window, user_limit, experience_limit). operations[i] is the call type and arguments[i] holds its arguments. Return a list of booleans, where entry i is True if call i was accepted and False otherwise.
Constraints
len(operations) == len(arguments), and each operation is either"allow"or"allow_multi".- Timestamps are integers and are nondecreasing across the whole sequence of calls.
window >= 1.global_limit,user_limitandexperience_limitare integers>= 0. A limit of0means every call it applies to is rejected.user_idandexperienceare strings.- The sequence may be long, so aim for amortized constant work per call.
Examples
Example 1
Input: simulate_throttle(['allow', 'allow', 'allow', 'allow'], [[0], [100], [999], [1000]], 2, 1000, 2, 2)
Output: [True, True, False, True]
Example 2
Input: simulate_throttle(['allow_multi', 'allow_multi', 'allow_multi', 'allow_multi'], [['u1', 'e1', 0], ['u1', 'e2', 1], ['u2', 'e1', 2], ['u1', 'e1', 1000]], 10, 1000, 2, 2)
Output: [True, True, True, True]
Example 3
Input: simulate_throttle(['allow_multi', 'allow_multi', 'allow_multi'], [['u', 'game', 0], ['u', 'game', 1], ['u', 'game', 2]], 10, 100, 2, 3)
Output: [True, True, False]
Hints
Hint 1
Only accepted calls matter. Because timestamps never decrease, the accepted timestamps for a key are already sorted, so a FIFO queue per key is enough.
Hint 2
Before deciding, remove from the front of a queue every timestamp s with s <= t - window. What remains is exactly the accepted calls inside [t - window + 1, t].
Hint 3
For allow_multi, evict from both the user queue and the experience queue and run both capacity checks first. Append the timestamp to both queues only when both checks pass.
Hint 4
Keep the global history and the per-key histories completely separate, and optionally delete keys whose queues become empty to keep memory small.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Only accepted calls matter for the limit, and only those still inside the window. Since timestamps never decrease, the accepted timestamps for any key are appended in sorted order. A FIFO queue (deque) per key therefore holds exactly what we need.
For a call at time t against a key's queue q:
- Evict. Pop from the front while
q[0] <= t - window. These timestamps lie outside[t - window + 1, t]. - Check. If
len(q) < limit, there is room. - Record. If accepted, append
t.
For "allow", this runs on a single global queue with global_limit.
For "allow_multi", we keep two dictionaries, one mapping user_id to a deque and one mapping experience to a deque. The steps are:
- Fetch or create both queues and evict stale entries from both.
- Compute
len(user_q) < user_limit and len(exp_q) < experience_limit. - Only if that is true, append
tto both queues.
All checks happen before any write, so the update is all-or-nothing. A rejection never uses up capacity on the other dimension.
After each multi-key call, any queue that is empty has its key removed. This covers limits of 0, where a key is created but never filled. Without it, rejected-only traffic would leave empty entries behind.
Why it is correct
- Sorted queues. We only append the current
t, andtnever decreases, so each queue stays sorted. - Complete eviction. Stale entries are always at the front, so popping while the front is
<= t - windowremoves all of them and nothing else. - Eviction stays valid. Later calls have larger or equal
t, so an entry that is stale now is stale forever. - Correct count. After eviction,
len(q)is the number of accepted calls in[t - window + 1, t], solen(q) < limitis exactly the acceptance rule. - Rejections are free. Rejected calls are never appended, so they do not count.
- Separate state. The global queue, user queues and experience queues are independent, as required.
Complexity
- Time: each accepted timestamp is appended once per queue and popped at most once, so each call is amortized O(1), plus the expected O(1) dictionary lookups. A single call can pop many entries, but that cost is paid for by earlier appends.
- Space: the global queue holds at most
global_limittimestamps. Each user queue holds at mostuser_limitand each experience queue at mostexperience_limit. Overall, space is proportional to the number of accepted calls still inside the window, with empty keys removed.
Reference solution
from collections import deque
from typing import List
def simulate_throttle(operations: List[str], arguments: List[List], global_limit: int, window: int, user_limit: int, experience_limit: int) -> List[bool]:
global_q = deque()
by_user = {}
by_experience = {}
answers = []
def evict(q, t):
cutoff = t - window
while q and q[0] <= cutoff:
q.popleft()
for op, args in zip(operations, arguments):
if op == "allow":
t = args[0]
evict(global_q, t)
if len(global_q) < global_limit:
global_q.append(t)
answers.append(True)
else:
answers.append(False)
elif op == "allow_multi":
user_id, experience, t = args
user_q = by_user.setdefault(user_id, deque())
exp_q = by_experience.setdefault(experience, deque())
evict(user_q, t)
evict(exp_q, t)
if len(user_q) < user_limit and len(exp_q) < experience_limit:
user_q.append(t)
exp_q.append(t)
answers.append(True)
else:
answers.append(False)
if not user_q:
del by_user[user_id]
if not exp_q:
del by_experience[experience]
else:
raise ValueError("unknown operation")
return answers