KatInterview

Sliding Window Stream Aggregator

Data Structure DesignAuto-graded · 18 test cases
MediumAuto-gradedData Structure Designsliding-windowdequedesign

Last 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 integer window_size. Returns None.
  • "record_metric": Ingests a data point given [timestamp, value]. Returns None.
  • "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, returns 0.0. Returns None if 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^9
  • 0 <= timestamp <= 10^9, provided in non-decreasing order across calls.
  • Total number of operations N is up to 10^5.
  • arguments[i] matches the parameter requirements of operations[i].
  • For "get_average", if no records have been added yet, return 0.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).