Sliding Window Stream Aggregator
Data Structure DesignAuto-graded · 18 test casesLast updated
Design a memory-efficient real-time streaming data structure to query moving averages over a sliding temporal window.
Design a telemetry tracking structure that computes the average value of streaming data points within a sliding time window of window_size seconds.
The system processes incoming data entries as (timestamp, value) pairs, where timestamp is an integer representing seconds and value is a float. Timestamps arrive in non-decreasing order.
You need to execute a series of operational commands provided as two parallel lists: operations and arguments.
The supported operations are:
"init": Initializes the data structure with a positive integerwindow_size. ReturnsNone."record_metric": Ingests a data point given[timestamp, value]. ReturnsNone."get_average": Returns a float representing the arithmetic mean of all recorded readings whose timestamps fall within the inclusive interval[latest_timestamp - window_size + 1, latest_timestamp]. If no points exist within this window, returns0.0. ReturnsNoneif called before any metric has been recorded.
To ensure low memory footprint during heavy traffic, multiple readings occurring at the exact same timestamp should be aggregated together into a single time bucket instead of stored as separate entries.
Constraints
1 <= window_size <= 10^90 <= timestamp <= 10^9, provided in non-decreasing order across calls.- Total number of operations
Nis up to10^5. arguments[i]matches the parameter requirements ofoperations[i].- For
"get_average", if no records have been added yet, return0.0. - The aggregate average must reflect every recorded metric point individually (i.e., total sum of readings divided by total count of readings within the active time frame).
Examples
Example 1
Input: metric_monitor_operations(['init', 'record_metric', 'record_metric', 'record_metric', 'get_average', 'record_metric', 'get_average'], [[3], [10, 50], [11, 60], [12, 70], [], [13, 80], []])
Output: [None, None, None, None, 60, None, 70]
Example 2
Input: metric_monitor_operations(['init', 'record_metric', 'record_metric', 'record_metric', 'get_average'], [[5], [100, 20], [100, 40], [104, 60], []])
Output: [None, None, None, None, 40]
Hints
Hint 1
Since timestamps are non-decreasing, old data points naturally expire from the front of the window in FIFO order. What data structure handles fast front removals and back insertions?
Hint 2
To minimize memory when multiple metrics arrive within the same second, store aggregated buckets containing `(timestamp, total_val, count)` rather than individual readings.
Hint 3
Maintain global running totals for both the sum of values and the count of items currently in the window to make query responses O(1).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The task requires tracking a running average over a sliding time window [latest_time - window_size + 1, latest_time]. Because timestamps are strictly non-decreasing, incoming data points naturally leave the window in First-In, First-Out (FIFO) order.
To solve this efficiently:
- Bucket Aggregation: Multiple metrics recorded during the exact same second are combined into a single bucket represented as
(timestamp, bucket_sum, bucket_count). This guarantees that the memory footprint never exceedsO(window_size)distinct entries, even under extremely high event frequency. - Double-Ended Queue (Deque): We use a
dequeto store the active time buckets. When a new metric arrives:- If its timestamp matches the most recent bucket, we merge it into that bucket.
- Otherwise, we push a new bucket onto the back of the queue.
- We update global tracking variables (
total_sumandtotal_count). - We purge expired buckets from the front of the queue whose timestamps fall before
latest_time - window_size + 1, adjustingtotal_sumandtotal_countaccordingly.
- Querying Average:
get_average()calculatestotal_sum / total_countin $O(1)$ time.
Complexity Analysis
- Time Complexity:
record_metric: Amortized $O(1)$. Each bucket is added once and removed at most once from the queue across all operations.get_average: $O(1)$ constant time lookup.- Overall stream processing takes $O(N)$ total time for $N$ operations.
- Space Complexity: $O(\min(N, \text{window_size}))$. In the worst case, we store at most one bucket per distinct second within the current sliding window.
Python Reference Code
from collections import deque
from typing import List, Union
class MetricMonitor:
def __init__(self, window_size: int):
self.window_size = window_size
self.current_time = None
self.total_sum = 0.0
self.total_count = 0
self.buckets = deque() # stores (timestamp, sum, count)
def record_metric(self, timestamp: int, value: float) -> None:
self.current_time = timestamp
# Group data arriving at the exact same second
if self.buckets and self.buckets[-1][0] == timestamp:
prev_ts, prev_sum, prev_cnt = self.buckets.pop()
updated_bucket = (prev_ts, prev_sum + value, prev_cnt + 1)
else:
updated_bucket = (timestamp, float(value), 1)
self.buckets.append(updated_bucket)
self.total_sum += value
self.total_count += 1
# Expire outdated buckets falling behind [timestamp - window_size + 1]
cutoff = timestamp - self.window_size + 1
while self.buckets and self.buckets[0][0] < cutoff:
_, evicted_sum, evicted_cnt = self.buckets.popleft()
self.total_sum -= evicted_sum
self.total_count -= evicted_cnt
def get_average(self) -> float:
if self.total_count == 0:
return 0.0
return self.total_sum / self.total_count
def metric_monitor_operations(operations: List[str], arguments: List[List[object]]) -> List[Union[None, float]]:
monitor = None
results = []
for op, args in zip(operations, arguments):
if op == "init":
monitor = MetricMonitor(args[0])
results.append(None)
elif op == "record_metric":
monitor.record_metric(args[0], args[1])
results.append(None)
elif op == "get_average":
results.append(monitor.get_average())
else:
raise ValueError(f"Unknown operation: {op}")
return results