Design Sliding-Window Average Tracker
Company: Decagon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Design a class that tracks records in a sliding time window.
Implement the following API:
- `init(time_window)`: initialize the object with a window size.
- `insert(record_id, value, timestamp)`: insert a new record.
- `get_avg(timestamp)`: return the average `value` of all records whose timestamps fall within the most recent `time_window` ending at `timestamp`.
Assumptions and requirements:
- `record_id` is unique for each inserted record.
- Timestamps are integers.
- Calls to `insert(...)` and `get_avg(...)` are made with non-decreasing timestamps.
- A record is considered active at time `t` if its timestamp is in the interval `[t - time_window + 1, t]`.
- If no records are active in the window, return `0`.
- The implementation should be optimized for the monotonic-timestamp constraint.
Follow-up:
- Support `update(record_id, new_timestamp)`, which changes the timestamp of an existing record while keeping its original value unchanged.
- Explain how your design would change if inserts and queries could arrive with out-of-order timestamps.
Quick Answer: This question evaluates design and implementation of a time-windowed tracking data structure, focusing on streaming aggregation, handling monotonic timestamps, efficient updates, and time/space trade-offs.