O(1) Sliding-Window Moving Average Runner
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Write an operation dispatcher run_sma(window_size, operations) that maintains the simple moving average over a sliding window holding at most window_size of the latest valid integer inputs:
def run_sma(window_size: int, operations: list[list]) -> list:
...
Process operations sequentially from left to right and append exactly one result per entry according to these rules:
["add", sample](wheresampleis a true Pythonint, excludingbool): insertsampleat the newest end of the active window, evict the oldest active sample if the count now exceedswindow_size, and appendNoneto the output list.["get_avg"]: compute and append the standard floating-point mean (active_sum / active_count) of all valid samples currently inside the window. While fewer thanwindow_sizevalid samples have been recorded, divide by the actual number of valid samples collected so far. If zero valid samples have been added yet, leave the window unchanged and append"ValueError".- Malformed or unrecognized entries (wrong command name, wrong argument count, non-sequence record, or non-integer sample such as a string, float,
None, or boolean): leave the active window completely untouched and append"ValueError".
Every valid operation must execute in O(1) time.
Examples
Example 1
Input:
window_size = 3
operations = [
["add", 4], ["get_avg"],
["add", 10], ["get_avg"],
["add", 16], ["add", -2], ["get_avg"]
]
Output: [None, 4.0, None, 7.0, None, None, 8.0]
Walk-through:
- ["add", 4] stores [4] (None), so the first ["get_avg"] returns 4 / 1 = 4.0.
- ["add", 10] expands the partial window to [4, 10] (None), giving 14 / 2 = 7.0 on the second ["get_avg"].
- ["add", 16] fills [4, 10, 16], and ["add", -2] evicts the oldest entry 4 to leave [10, 16, -2], whose mean is 24 / 3 = 8.0.
Example 2
Input:
window_size = 2
operations = [
["get_avg"],
["add", 6],
["add", "bad"],
["reset"],
["get_avg"],
["add", 9],
["add", 5],
["get_avg"]
]
Output: ["ValueError", None, "ValueError", "ValueError", 6.0, None, None, 7.0]
Walk-through:
- Querying ["get_avg"] on an empty window appends "ValueError".
- ["add", 6] sets the window to [6]. Both ["add", "bad"] and ["reset"] are rejected with "ValueError" without altering [6], so the next ["get_avg"] returns 6.0.
- Adding 9 and then 5 evicts 6, leaving [9, 5] with average 14 / 2 = 7.0.
Constraints
1 <= window_size <= 200_000- Every valid integer sample fits in a signed 64-bit integer (
-2^63through2^63 - 1). - At every point in execution, the sum of elements currently inside the active window also fits in a signed 64-bit integer.
Step-by-step walkthrough
Understand the operations and validation rules
We are given a positive
window_sizek(1 <= k <= 200,000) and a list of operation records, and we must return a result list with one entry per operation:Operation record Effect on sliding window Appended output -------------------------------------------------------------------------------------- ["add", sample] (int) Add sample; evict oldest if size > k None ["get_avg"] (window > 0) No state change total / count (float) ["get_avg"] (window == 0) No state change "ValueError" Malformed / unknown record No state change "ValueError"Notice three important contract details before writing code: - Partial windows: Before
kvalid samples have arrived, divide by the number of valid samples received so far (1, 2, ..., k - 1), not byk. - No exceptions escape: Instead of raisingValueError, we append the literal string"ValueError"to the output list and keep processing subsequent operations with the window state completely untouched. - Strict integer check: Records like["add"],["add", 1, 2],["get_avg", 0],["add", "bad"],"get_avg", or["add", True]are all malformed. In Python,boolis a subclass ofint(isinstance(True, int)evaluates toTrue!), so checkingnot isinstance(sample, bool)keeps booleans from sneaking in as1or0.Why recomputing the sum on every query is too slow
The straightforward beginner approach appends every valid sample to a list and slices the last
kelements whenever["get_avg"]arrives:Naive query: recent = samples[-k:] avg = sum(recent) / len(recent) --> O(k) work per get_avg!With
k = 200,000and200,000queries, summing200,000numbers per query performs roughly4 * 10^10additions — taking tens of seconds instead of milliseconds. Keeping all historical samples forever also wastes memory when the stream runs for millions of updates. To achieve true O(1) time per operation, we must update our sum incrementally rather than resumming from scratch.Key idea: Maintain a bounded FIFO queue and an exact integer sum
Think about what changes when a new sample enters a full window of size
k = 3:Before ["add", -2]: window = [4, 10, 16] total = 30 Step 1 (enter -2): window = [4, 10, 16, -2] total = 30 + (-2) = 28 Step 2 (evict 4): window = [10, 16, -2] total = 28 - 4 = 24 --> average = 24 / 3 = 8.0We only ever need two pieces of state: 1. A FIFO (First-In, First-Out) queue storing at most
kactive samples so we know which sample is oldest when it is time to evict. Python'scollections.deque(a double-ended queue) supportsappend(sample)on the right andpopleft()from the left in O(1) time — unlike a plain Pythonlist, wherelist.pop(0)shifts allk - 1remaining elements in O(k) time. 2. An exact integer running sumself.total. Whyintinstead offloat? Because IEEE-754 floating-point numbers have only ~15–17 decimal digits of precision (floating-point precision loss):1e18 + 1.0rounds straight back to1e18! Ifwindow_size = 2saw10**18,1,1, afloatrunning sum would compute(1e18 + 1.0 + 1.0) - 1e18 = 0.0instead of2! Python'sintis exact, so we convert tofloatonly once inside/when answeringaverage().from collections import deque class MovingAverage: """Fixed-size sliding window maintaining active samples and their exact integer sum.""" def __init__(self, window_size: int) -> None: self.window_size = window_size # window: FIFO deque of up to window_size ints, oldest on the left, e.g. deque([10, 16, -2]). self.window = deque() # total: exact Python int sum of self.window (avoids floating-point rounding drift). self.total = 0 def add(self, sample: int) -> None: # Phase 1: Append newest sample on the right and include it in the running sum. self.window.append(sample) self.total += sample # Phase 2: If the window now exceeds capacity, evict the oldest sample from the left in O(1). if len(self.window) > self.window_size: oldest = self.window.popleft() self.total -= oldest def count(self) -> int: return len(self.window) def average(self) -> float: # Convert to float only once at query time by dividing exact sum by active sample count. return self.total / len(self.window)Validate each operation record before touching state
To guarantee that malformed or unknown operations leave the sliding window untouched, check every structural condition before mutating
MovingAverage. Checkingisinstance(op, (list, tuple))andlen(op)first preventsTypeErrororIndexErrorwhen a record isNone, a bare string"get_avg", or an empty list[]:def is_add(op) -> bool: """Return True iff op has the exact shape ["add", int_sample].""" if not isinstance(op, (list, tuple)) or len(op) != 2: return False if op[0] != "add": return False sample = op[1] # In Python bool subclasses int (isinstance(True, int) is True), so reject bool explicitly. return isinstance(sample, int) and not isinstance(sample, bool) def is_get_avg(op) -> bool: """Return True iff op has the exact shape ["get_avg"].""" return isinstance(op, (list, tuple)) and len(op) == 1 and op[0] == "get_avg"Write the top-level operation runner
Now
run_smabecomes a clean three-way dispatch per operation: 1. Validadd-> updatesmaand appendNone. 2. Validget_avgwhensma.count() > 0-> appendsma.average(). 3. Everything else (malformed record, unknown command name, orget_avgwhensma.count() == 0) -> leavesmauntouched and append"ValueError".from typing import List def run_sma(window_size: int, operations: List[list]) -> list: sma = MovingAverage(window_size) results = [] for op in operations: # Validate completely before mutating sma so malformed records leave state untouched. if is_add(op): sma.add(op[1]) results.append(None) elif is_get_avg(op) and sma.count() > 0: results.append(sma.average()) else: # Covers malformed records, unknown commands, and get_avg on an empty window. results.append("ValueError") return resultsTrace Example 1 step by step
Let's walk through Example 1 with
window_size = 3:Step Operation Action on deque & total Window total Output ------------------------------------------------------------------------------------------------ 1 ["add", 4] append 4; total = 0 + 4 [4] 4 None 2 ["get_avg"] count = 1 (< 3, average available items) [4] 4 4.0 3 ["add", 10] append 10; total = 4 + 10 [4, 10] 14 None 4 ["get_avg"] count = 2 -> 14 / 2 [4, 10] 14 7.0 5 ["add", 16] append 16; total = 14 + 16 (window full) [4, 10, 16] 30 None 6 ["add", -2] append -2 (total=28); len 4 > 3 -> pop 4 [10, 16, -2] 24 None 7 ["get_avg"] count = 3 -> 24 / 3 [10, 16, -2] 24 8.0Final output list:
[None, 4.0, None, 7.0, None, None, 8.0].Complete solution
Here is the complete solution ready to submit:
from typing import List from collections import deque def is_add(op) -> bool: """Return True iff op has the exact shape ["add", int_sample].""" if not isinstance(op, (list, tuple)) or len(op) != 2: return False if op[0] != "add": return False sample = op[1] # In Python bool subclasses int (isinstance(True, int) is True), so reject bool explicitly. return isinstance(sample, int) and not isinstance(sample, bool) def is_get_avg(op) -> bool: """Return True iff op has the exact shape ["get_avg"].""" return isinstance(op, (list, tuple)) and len(op) == 1 and op[0] == "get_avg" class MovingAverage: """Fixed-size sliding window maintaining active samples and their exact integer sum.""" def __init__(self, window_size: int) -> None: self.window_size = window_size # window: FIFO deque of up to window_size ints, oldest on the left, e.g. deque([10, 16, -2]). self.window = deque() # total: exact Python int sum of self.window (avoids floating-point rounding drift). self.total = 0 def add(self, sample: int) -> None: # Phase 1: Append newest sample on the right and include it in the running sum. self.window.append(sample) self.total += sample # Phase 2: If the window now exceeds capacity, evict the oldest sample from the left in O(1). if len(self.window) > self.window_size: oldest = self.window.popleft() self.total -= oldest def count(self) -> int: return len(self.window) def average(self) -> float: # Convert to float only once at query time by dividing exact sum by active sample count. return self.total / len(self.window) def run_sma(window_size: int, operations: List[list]) -> list: sma = MovingAverage(window_size) results = [] for op in operations: # Validate completely before mutating sma so malformed records leave state untouched. if is_add(op): sma.add(op[1]) results.append(None) elif is_get_avg(op) and sma.count() > 0: results.append(sma.average()) else: # Covers malformed records, unknown commands, and get_avg on an empty window. results.append("ValueError") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine tracking the average weight of up to k passengers currently inside an elevator: instead of asking everyone inside to step onto a scale from scratch every time someone asks for the average, you write one running total on a whiteboard — add each newcomer's weight as they enter the back door, and subtract the earliest rider's weight as they exit the front door! To remember whose weight exits next, we line active samples up in a deque (a double-ended FIFO — First-In, First-Out — queue that adds to the back and removes from the front in constant time) alongside an exact integer total.
The naive approach stores every sample ever seen and calls sum(samples[-k:]) / len(samples[-k:]) on each ["get_avg"] (or evicts from a Python list via list.pop(0)). Both fail the O(1) requirement: re-summing k elements costs O(k) per query, and list.pop(0) shifts k - 1 items in memory at O(k) per add, turning 200,000 operations at window_size = 200,000 into tens of billions of steps.
Walk through Example 1 with window_size = 3 and samples 4, 10, 16, -2:
- ["add", 4] then ["get_avg"]: window = [4], total = 4 -> returns 4 / 1 = 4.0.
- ["add", 10] then ["get_avg"]: window = [4, 10], total = 14 -> returns 14 / 2 = 7.0 (fewer than 3 samples so far, so we divide by 2).
- ["add", 16] then ["add", -2]: 16 fills [4, 10, 16] (total = 30); when -2 arrives, total becomes 30 + (-2) = 28, then len (4) exceeds 3, so 4 pops off the left (total = 28 - 4 = 24, window = [10, 16, -2]), and ["get_avg"] returns 24 / 3 = 8.0 in a single division!
Complexity
- Time: O(1) per operation (and O(n) total across
noperations) becauseis_addandis_get_avginspect at most two elements,deque.appendanddeque.popleftrun in O(1) pointer updates, and 64-bit integer addition/subtraction/division take constant time. - Space: O(min(m, k)) auxiliary memory for the sliding window (where
mis valid adds andkiswindow_size, sinceself.windowholds at mostkintegers at once), plus O(n) for the required output list ofnresults.
Edge cases
["get_avg"]before any valid["add"]: Appends"ValueError"and leaves the window empty so later valid["add", 6]calls still succeed cleanly (6.0). Also, a malformed["add", "bad"]does not add anything, so a["get_avg"]right after it on an empty window still returns"ValueError".window_size = 1: Every validaddafter the first immediately pops the previous sample, soget_avgalways equals the single most recent valid sample.- Stream shorter than
window_size: Withwindow_size = 200_000and three samples10, 20, 30,len(self.window)is3, returning60 / 3 = 20.0rather than dividing by200_000. - Extreme 64-bit integers and cancellation: Adding
10**18,1,1withwindow_size = 2evicts10**18cleanly becauseself.totalis an exact Pythonint, yielding(1 + 1) / 2 = 1.0with zero floating-point precision loss (rounding error caused by limited mantissa bits infloat). - Malformed shapes, wrong case, and booleans:
[],["add"],["add", 1, 2],["get_avg", 3],"get_avg",["ADD", 1], and["add", True]all safely return"ValueError"without mutating state or raisingIndexError/TypeError.
Common mistakes
- Calling
sum(self.window)insideaverage(). Passes small unit tests effortlessly, then times out on large windows (O(k)per query instead ofO(1)). - Evicting with
list.pop(0)instead ofcollections.deque.popleft(). Removing index0of a Pythonlistshifts every remaining element left, costingO(k)peraddonce the window fills. - Accumulating
self.totalas afloat. Repeated float additions and subtractions accumulate rounding drift and lose small numbers next to large ones ((1e18 + 1.0) - 1e18 == 0.0). - Dividing by
self.window_sizeinstead oflen(self.window). Gives wrong answers during the warm-up period beforekvalid samples have arrived. - Mutating state before validating
op. Appendingop[1]first and checking its type afterward corruptsself.windowon malformed inputs like["add", "bad"]. - Raising
raise ValueError(...)instead of appending"ValueError". The specification requires returning"ValueError"inside the output list and continuing execution.
Alternative approaches
- Preallocated ring buffer (circular array): A ring buffer is a fixed-length array
[0] * kwhere sampleioverwrites sloti % kin a circle, avoiding dynamic node allocations. It is also O(1) time per operation and very cache-friendly in C++/Java, though in Pythondequeavoids preallocating200,000slots when only a handful of samples arrive. deque(maxlen=window_size): Automatically drops the oldest item onappend, which saves a line of code — but because it drops silently, you must remember to checkif len(window) == window_size: total -= window[0]before appending, whereas explicitpopleft()afterappendis harder to get wrong.
Follow-up questions
- How would you prevent transient 64-bit integer overflow when implementing this in C++ or Java? Even though every active window sum fits in signed 64 bits, an intermediate sum during update can transiently overflow: with
k = 3and window[-2^62, 2^62, 2^62](sum+2^62), evicting-2^62first hits+2^63(overflow!), while on[2^62, 2^62, -2^62]adding+2^62first also hits+2^63! In Java,longwraps modulo2^64safely so the final sum is always exact; in C++ (where signed overflow is undefined behavior), perform the running addition and subtraction in unsigneduint64_t(well-defined modulo2^64wrap-around) and cast back toint64_t(or use__int128). - How does the design change if the window tracks samples from the past T seconds rather than the last k samples? Store
(timestamp, sample)pairs inself.window. Whenever anaddorget_avgarrives at timestampnow, pop from the left whileself.window[0][0] <= now - Tand subtract each expired sample fromself.total. Although a single call might pop many expired items at once, each sample enters and leaves the deque at most once across the entire run, giving amortized O(1) time per operation (meaning the average cost per operation over any sequence ofnoperations is O(1)). - Could you extend the structure to answer get_max or get_median queries efficiently alongside get_avg? For
get_max, maintain a second monotonic deque (a deque kept sorted from largest to smallest by popping smaller elements from the back before inserting a new sample, and popping the front when it slides out of the window), givingget_maxin O(1) query time and amortized O(1) peradd. Exactget_mediancannot be maintained in O(1) for arbitrary 64-bit integers, so use two heaps (a max-heap for the lower half and a min-heap for the upper half with lazy deletion of evicted elements) for O(1)get_medianand O(log k) peradd.
Follow-up questions
- How would you prevent transient 64-bit integer overflow when implementing this in C++ or Java?
- How does the design change if the window tracks samples from the past T seconds rather than the last k samples?
- Could you extend the structure to answer get_max or get_median queries efficiently alongside get_avg?
Similar questions
- Arrival-Ordered Market Quote Store
- Iterative Deep Merge of Dictionaries
- Reflecting on an Engineering Setback and Lasting Habits
- Inline Pre-Trade Risk Engine for Automated Trading
- Custom C++ UniquePtr and Resizable Vector Templates
- Balancing Peer Coaching and Delivery Under Engineering Roadblocks
More Chicago Trading Company interview questions
- Arrival-Ordered Market Quote Store Medium
- Reflecting on an Engineering Setback and Lasting Habits Medium
- Inline Pre-Trade Risk Engine for Automated Trading Medium Pro
- Custom C++ UniquePtr and Resizable Vector Templates Medium Pro
- Iterative Deep Merge of Dictionaries Easy Pro
- Balancing Peer Coaching and Delivery Under Engineering Roadblocks Medium Pro
- 48-Bit Virtual Address Translation Across TLB, Page Tables, and L1D Medium Pro