Cache, Quota Gate and Burst Counter: Batch Operation Runner
Data Structure DesignAuto-graded · 21 test casesLast updated
Simulate a batch of operations on an O(1) LFU cache, a fixed-window per-user quota check, and a two-pointer peak request counter.
Cache, Quota Gate and Burst Counter
You are building the core of a small service that bundles three independent features. You are given the configuration of the service and a list of operations to execute in order. Return the result of each operation.
Features
1. LFU cache with at most capacity entries, mapping integer keys to integer values.
get_cache(key): if the key is present, return its value and count this as a use of the key. If it is absent, return-1and change nothing.put_cache(key, value): if the key already exists, overwrite its value and count this as a use. Do not evict anything in this case. If the key is new and the cache is already full, first evict the entry with the smallest use count. If several entries share that smallest count, evict the one that was used least recently. Then insert the new key with a use count of 1.- A newly inserted key has a use count of 1. Every successful
get_cacheand everyput_cacheon an existing key increases the count by 1. - If
capacityis 0,put_cachedoes nothing. - Both cache operations are expected to run in O(1) time.
2. Fixed-window quota gate
is_allowed(user_id, current_time): time is divided into consecutive windows of lengthwindow_size. The window of a request iscurrent_time // window_size.- Each user may have at most
limitaccepted requests in each window. Counts are tracked per user and per window independently. - If the user's accepted count in that window is below
limit, accept the request (returntrue) and increase the count. Otherwise returnfalse. Rejected requests do not consume quota.
3. Peak burst counter
max_throughput(timestamps):timestampsis a list of request times sorted in non-decreasing order. Find the largest number of requests that fit inside one window of lengthwindow_size, where a group of requests fits iflatest - earliest <= window_size(both ends inclusive). Duplicate timestamps each count. An empty list gives0.
The cache and the quota gate keep their state across all operations in the call. max_throughput depends only on the list passed to it.
Input
capacity,limit,window_size: the configuration described above.window_sizeis used by both the quota gate and the burst counter.operations: a list of strings, each one of"get_cache","put_cache","is_allowed","max_throughput".arguments: a list with the same length asoperations. The entry at indexiholds the arguments foroperations[i]:get_cache:[key]put_cache:[key, value]is_allowed:[user_id, current_time]max_throughput:[timestamps]
Output
A list with one entry per operation, in order:
get_cache: the value, or-1on a miss.put_cache:None.is_allowed: a boolean.max_throughput: an integer.
Constraints
capacity,limitandwindow_sizeare non-negative integers up to 10^5.window_sizeis at least 1.len(operations) == len(arguments).- Every operation name is one of the four listed above.
- Each
timestampslist is sorted in non-decreasing order. - Keys, values, user ids and times are integers.
Examples
Example 1
Input: process_service_ops(2, 2, 250, ['put_cache', 'put_cache', 'get_cache', 'put_cache', 'get_cache', 'max_throughput'], [[1, 1], [2, 2], [1], [3, 3], [2], [[100, 200, 300, 500, 600]]])
Output: [None, None, 1, None, -1, 3]
Example 2
Input: process_service_ops(1, 1, 10, ['is_allowed', 'is_allowed', 'is_allowed', 'is_allowed'], [[7, 0], [7, 1], [7, 10], [8, 1]])
Output: [True, False, True, True]
Example 3
Input: process_service_ops(2, 2, 100, ['put_cache', 'put_cache', 'get_cache', 'put_cache', 'get_cache', 'get_cache'], [[1, 10], [2, 20], [1], [3, 30], [2], [3]])
Output: [None, None, 10, None, -1, 30]
Hints
Hint 1
For the cache, group keys by use count. Within each group keep keys in order of last use, for example with an OrderedDict per count, and track the smallest count currently present.
Hint 2
When a key's count goes from f to f+1, remove it from group f and append it to group f+1. If group f was the minimum and is now empty, the minimum becomes f+1. A fresh insert always resets the minimum to 1.
Hint 3
For the quota gate, key a counter by (user_id, current_time // window_size). For the burst counter, slide a left pointer forward while timestamps[right] - timestamps[left] > window_size.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The three features are independent, so handle each with its own state while looping over the operations in order.
LFU cache in O(1)
Keep three things:
store: key -> (value, use count).buckets: use count -> anOrderedDictof keys. Keys are appended when they enter a bucket, so the front of each bucket is the least recently used key with that count.min_count: the smallest use count currently present.
Touching a key (a get hit, or a put on an existing key) removes it from bucket f and appends it to bucket f+1. If bucket f becomes empty and f == min_count, then min_count becomes f+1.
Inserting a new key into a full cache first evicts the front of buckets[min_count], which is the least frequently used key and, among ties, the least recently used one. The new key then enters bucket 1 and min_count becomes 1. A put on an existing key never evicts. With capacity == 0, put does nothing.
Why it is correct: each key is in exactly one bucket, matching its count. A key's position within a bucket changes only when it enters the bucket, so bucket order equals recency order. min_count stays exact because a touch can only empty the minimum bucket by moving its key into min_count + 1, and an insert always creates count 1, which is the global minimum.
Fixed-window quota gate
Map each request to (user_id, current_time // window_size) and keep a counter per pair. Accept only when the counter is below limit, and increment it only on acceptance, so rejected requests cost nothing.
Peak burst counter
With sorted timestamps, use two pointers. For each right index, advance left while ts[right] - ts[left] > window_size. The window [left, right] is then the largest valid group ending at right, and the answer is the maximum of right - left + 1. left only moves forward, since a start that is too early for one right is also too early for every later one.
Complexity
get_cache/put_cache: O(1) time each, O(capacity) space.is_allowed: O(1) time, O(number of distinct user and window pairs) space.max_throughput: O(n) time for a list of n timestamps, O(1) extra space.
Reference solution
from collections import defaultdict, OrderedDict
from typing import List
def process_service_ops(capacity: int, limit: int, window_size: int, operations: List[str], arguments: List[List]) -> List:
store = {} # key -> (value, use_count)
buckets = defaultdict(OrderedDict) # use_count -> keys, oldest use first
min_count = 0
quota = {} # (user_id, window_id) -> accepted count
results = []
def bump(key, new_value=None, replace=False):
nonlocal min_count
value, count = store[key]
del buckets[count][key]
if not buckets[count] and min_count == count:
min_count += 1
if replace:
value = new_value
store[key] = (value, count + 1)
buckets[count + 1][key] = None
return value
for op, args in zip(operations, arguments):
if op == "get_cache":
key = args[0]
if key not in store:
results.append(-1)
else:
results.append(bump(key))
elif op == "put_cache":
key, value = args
if capacity > 0:
if key in store:
bump(key, value, True)
else:
if len(store) >= capacity:
evicted, _ = buckets[min_count].popitem(last=False)
del store[evicted]
store[key] = (value, 1)
buckets[1][key] = None
min_count = 1
results.append(None)
elif op == "is_allowed":
user_id, current_time = args
slot = (user_id, current_time // window_size)
used = quota.get(slot, 0)
ok = used < limit
if ok:
quota[slot] = used + 1
results.append(ok)
elif op == "max_throughput":
ts = args[0]
left = 0
best = 0
for right, t in enumerate(ts):
while t - ts[left] > window_size:
left += 1
best = max(best, right - left + 1)
results.append(best)
else:
raise ValueError(f"Unknown operation: {op}")
return results