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] (where sample is a true Python int, excluding bool): insert sample at the newest end of the active window, evict the oldest active sample if the count now exceeds window_size, and append None to 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 than window_size valid 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^63 through 2^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

  1. Understand the operations and validation rules

    We are given a positive window_size k (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 k valid samples have arrived, divide by the number of valid samples received so far (1, 2, ..., k - 1), not by k. - No exceptions escape: Instead of raising ValueError, 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, bool is a subclass of int (isinstance(True, int) evaluates to True!), so checking not isinstance(sample, bool) keeps booleans from sneaking in as 1 or 0.

  2. 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 k elements whenever ["get_avg"] arrives:

    Naive query:  recent = samples[-k:]
                  avg    = sum(recent) / len(recent)   -->  O(k) work per get_avg!
    

    With k = 200,000 and 200,000 queries, summing 200,000 numbers per query performs roughly 4 * 10^10 additions — 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.

  3. 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.0
    

    We only ever need two pieces of state: 1. A FIFO (First-In, First-Out) queue storing at most k active samples so we know which sample is oldest when it is time to evict. Python's collections.deque (a double-ended queue) supports append(sample) on the right and popleft() from the left in O(1) time — unlike a plain Python list, where list.pop(0) shifts all k - 1 remaining elements in O(k) time. 2. An exact integer running sum self.total. Why int instead of float? Because IEEE-754 floating-point numbers have only ~15–17 decimal digits of precision (floating-point precision loss): 1e18 + 1.0 rounds straight back to 1e18! If window_size = 2 saw 10**18, 1, 1, a float running sum would compute (1e18 + 1.0 + 1.0) - 1e18 = 0.0 instead of 2! Python's int is exact, so we convert to float only once inside / when answering average().

    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)
    
  4. 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. Checking isinstance(op, (list, tuple)) and len(op) first prevents TypeError or IndexError when a record is None, 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"
    
  5. Write the top-level operation runner

    Now run_sma becomes a clean three-way dispatch per operation: 1. Valid add -> update sma and append None. 2. Valid get_avg when sma.count() > 0 -> append sma.average(). 3. Everything else (malformed record, unknown command name, or get_avg when sma.count() == 0) -> leave sma untouched 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 results
    
  6. Trace 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.0
    

    Final output list: [None, 4.0, None, 7.0, None, None, 8.0].

  7. 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 n operations) because is_add and is_get_avg inspect at most two elements, deque.append and deque.popleft run 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 m is valid adds and k is window_size, since self.window holds at most k integers at once), plus O(n) for the required output list of n results.

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 valid add after the first immediately pops the previous sample, so get_avg always equals the single most recent valid sample.
  • Stream shorter than window_size: With window_size = 200_000 and three samples 10, 20, 30, len(self.window) is 3, returning 60 / 3 = 20.0 rather than dividing by 200_000.
  • Extreme 64-bit integers and cancellation: Adding 10**18, 1, 1 with window_size = 2 evicts 10**18 cleanly because self.total is an exact Python int, yielding (1 + 1) / 2 = 1.0 with zero floating-point precision loss (rounding error caused by limited mantissa bits in float).
  • 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 raising IndexError/TypeError.

Common mistakes

  • Calling sum(self.window) inside average(). Passes small unit tests effortlessly, then times out on large windows (O(k) per query instead of O(1)).
  • Evicting with list.pop(0) instead of collections.deque.popleft(). Removing index 0 of a Python list shifts every remaining element left, costing O(k) per add once the window fills.
  • Accumulating self.total as a float. 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_size instead of len(self.window). Gives wrong answers during the warm-up period before k valid samples have arrived.
  • Mutating state before validating op. Appending op[1] first and checking its type afterward corrupts self.window on 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] * k where sample i overwrites slot i % k in a circle, avoiding dynamic node allocations. It is also O(1) time per operation and very cache-friendly in C++/Java, though in Python deque avoids preallocating 200,000 slots when only a handful of samples arrive.
  • deque(maxlen=window_size): Automatically drops the oldest item on append, which saves a line of code — but because it drops silently, you must remember to check if len(window) == window_size: total -= window[0] before appending, whereas explicit popleft() after append is 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 = 3 and window [-2^62, 2^62, 2^62] (sum +2^62), evicting -2^62 first hits +2^63 (overflow!), while on [2^62, 2^62, -2^62] adding +2^62 first also hits +2^63! In Java, long wraps modulo 2^64 safely so the final sum is always exact; in C++ (where signed overflow is undefined behavior), perform the running addition and subtraction in unsigned uint64_t (well-defined modulo 2^64 wrap-around) and cast back to int64_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 in self.window. Whenever an add or get_avg arrives at timestamp now, pop from the left while self.window[0][0] <= now - T and subtract each expired sample from self.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 of n operations 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), giving get_max in O(1) query time and amortized O(1) per add. Exact get_median cannot 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_median and O(log k) per add.

Follow-up questions

Similar questions

More Chicago Trading Company interview questions

All 8 Chicago Trading Company questions →