Sliding Window Request Rate Calculator
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests the ability to implement time-bucketed sliding-window aggregation with efficient memory usage and amortized constant-time operations.
Build an in-memory request rate tracker that processes a stream of operations.
You must handle two types of operations:
"record"with parameters[key, timestamp]: log that a request for the given key occurred at the specified timestamp"get_qps"with parameters[key, now]: calculate and return the average requests per second for the key over a 5-minute sliding window ending atnow
Specification
The sliding window spans exactly 300 seconds: [now - 299, now] inclusive at both endpoints.
The queries-per-second value is computed as: (total requests in window) / 300.0
Return results as a list in the same order as operations:
"record"operations produceNone(ornull)"get_qps"operations produce a float
Behavior
- Timestamps are non-negative integers representing seconds
- Operations arrive in non-decreasing timestamp order
- Multiple requests may share the same key and timestamp
- A key with no recorded requests returns
0.0 - A key whose requests have all expired (fallen outside the window) returns
0.0 - The divisor is always 300.0, even when fewer than 300 seconds of data exist
Constraints
- 1 ≤ number of operations ≤ 100,000
- 0 ≤ timestamp ≤ 10^9
- 1 ≤ key length ≤ 50
- All timestamps in the operation sequence are non-decreasing
Examples
Example 1
Input: calculate_request_rates(['record', 'get_qps', 'record', 'record', 'get_qps', 'get_qps'], [['api', 100], ['api', 100], ['api', 101], ['worker', 101], ['api', 101], ['worker', 101]])
Output: [None, 0.0033333333333333335, None, None, 0.006666666666666667, 0.0033333333333333335]
Example 2
Input: calculate_request_rates(['record', 'get_qps', 'get_qps'], [['api', 1], ['api', 300], ['api', 301]])
Output: [None, 0.0033333333333333335, 0]
Hints
Hint 1
Store request counts grouped by timestamp rather than storing each individual request to save memory
Hint 2
Use a queue structure to efficiently expire old data from the front as time advances
Hint 3
Maintain a running sum of requests in the current window to avoid recounting on every query
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is maintaining a 5-minute sliding window efficiently as time advances. The key insights are:
-
Bucket requests by timestamp: Instead of storing each request individually, group them by the second they occurred in. Store
(timestamp, count)pairs. -
Use a queue for natural expiration: Since timestamps only increase, old data always expires from the front. A double-ended queue (deque) allows efficient append at the back and removal from the front.
-
Maintain a running total: Keep a cached sum of all request counts currently in the window, updating it incrementally as buckets are added or removed.
For each key, we maintain:
- A deque of
(timestamp, count)tuples in chronological order - A running total of requests in the current window
Operations
Record:
- Compute the window start:
timestamp - 299 - Remove expired buckets from the front, subtracting their counts from the total
- If the last bucket has the same timestamp, increment its count; otherwise append a new bucket
- Increment the total and return
None
Get QPS:
- Compute the window start:
now - 299 - Remove expired buckets from the front, subtracting their counts from the total
- Divide the total by 300.0 and return
Note that queries also perform expiration. This is correct because any future operation will have a timestamp ≥ now and would expire the same buckets anyway.
Why It Works
The window [now - 299, now] contains exactly 300 distinct seconds. We maintain the invariant that after processing an operation at time t, the deque contains only buckets with timestamps in [t - 299, t], and the total equals the sum of their counts.
Expiration preserves this: since buckets are stored in increasing order and we stop at the first bucket ≥ window_start, all remaining buckets are within the window.
Complexity
Time: O(1) amortized per operation. Each bucket is appended once and removed at most once. While a single operation might remove many buckets, the total removal work across all operations is bounded by the number of buckets created.
Space: O(min(300, D) × K) where D is the number of distinct seconds with requests and K is the number of keys. In the worst case, this is O(300K) per key regardless of request volume. A million requests in one second uses just one bucket.
Edge Cases
- Querying a key that was never recorded returns
0.0 - A key whose requests have all aged out has an empty deque and returns
0.0 - Multiple requests in the same second collapse into one bucket
- The divisor is always 300, even with fewer than 300 seconds of history
from collections import deque
from typing import Deque, Dict, List, Optional, Tuple
def calculate_request_rates(operations: List[str], arguments: List[List[object]]) -> List[Optional[float]]:
key_buckets: Dict[str, Deque[Tuple[int, int]]] = {}
key_totals: Dict[str, int] = {}
output: List[Optional[float]] = []
for op, params in zip(operations, arguments):
if op == "record":
key, ts = params
buckets = key_buckets.setdefault(key, deque())
current_total = key_totals.get(key, 0)
# Remove expired buckets
window_start = ts - 299
while buckets and buckets[0][0] < window_start:
_, expired_count = buckets.popleft()
current_total -= expired_count
# Merge into existing bucket or create new one
if buckets and buckets[-1][0] == ts:
prev_ts, prev_count = buckets[-1]
buckets[-1] = (prev_ts, prev_count + 1)
else:
buckets.append((ts, 1))
key_totals[key] = current_total + 1
output.append(None)
elif op == "get_qps":
key, now = params
buckets = key_buckets.get(key)
if buckets is None:
output.append(0.0)
continue
current_total = key_totals.get(key, 0)
# Remove expired buckets
window_start = now - 299
while buckets and buckets[0][0] < window_start:
_, expired_count = buckets.popleft()
current_total -= expired_count
key_totals[key] = current_total
output.append(current_total / 300.0)
else:
raise ValueError(f"Unknown operation: {op}")
return output