Sliding-Window Mean With IEEE-754 Infinities and NaNs

Medium · Software Engineering Fundamentals · Data Scientist · Online Assessment

Problem Statement

Telemetry and financial signal streams often interleave ordinary floating-point readings with IEEE-754 special markers: NaN (missing or corrupt sample), +inf (positive saturation), and -inf (negative saturation). Updating a naive rolling sum with total += incoming - outgoing breaks as soon as a special value slides through, because NaN - NaN and inf - inf both evaluate to NaN and corrupt every window that follows.

Implement sliding_window_mean(nums, k) to return the arithmetic mean of every contiguous subarray nums[s : s + k] of length k (for 0 <= s <= len(nums) - k; return an empty sequence if k <= 0 or k > len(nums)).

Python signature (used by the test runner):

def sliding_window_mean(nums: List[float], k: int) -> List[float]:

Equivalent C++ signature:

std::vector<float> sliding_window_mean(const std::vector<float>& nums, int k);

Evaluate each window of length k using the following strict precedence order:

  1. NaN dominance: If one or more elements inside the window are NaN, the window's result is NaN (even when infinities are also present).
  2. Opposing infinities: If the window contains no NaN, at least one +inf, and at least one -inf, the sum has an indeterminate sign, so the window's result is NaN.
  3. Positive infinity: If the window contains +inf and neither NaN nor -inf, the window's result is +inf.
  4. Negative infinity: If the window contains -inf and neither NaN nor +inf, the window's result is -inf.
  5. All finite entries: When all k elements are finite, return (nums[s] + ... + nums[s + k - 1]) / k without losing precision to earlier large-magnitude values.
  6. Zero residual corruption: Once any NaN, +inf, -inf, or extreme finite spike slides out of the window, later windows must compute clean, uncorrupted results.

Examples

Example 1

Input:  nums = [3.0, NaN, 6.0, 9.0, 12.0], k = 3
Output: [NaN, NaN, 9.0]

Walk-through: - nums[0:3] = [3.0, NaN, 6.0] contains NaN, producing NaN. - nums[1:4] = [NaN, 6.0, 9.0] still contains NaN, producing NaN. - nums[2:5] = [6.0, 9.0, 12.0] has evicted NaN; all three values are finite, so the mean is (6.0 + 9.0 + 12.0) / 3 = 9.0.

Example 2

Input:  nums = [5.0, inf, -inf, 2.0, 6.0], k = 2
Output: [inf, NaN, -inf, 4.0]

Walk-through: - nums[0:2] = [5.0, inf] holds +inf with no NaN or -inf, producing inf. - nums[1:3] = [inf, -inf] holds both +inf and -inf, producing NaN. - nums[2:4] = [-inf, 2.0] holds only -inf plus a finite value, producing -inf. - nums[3:5] = [2.0, 6.0] is purely finite after -inf leaves, producing (2.0 + 6.0) / 2 = 4.0.

Example 3

Input:  nums = [NaN, inf, 10.0, 20.0], k = 2
Output: [NaN, inf, 15.0]

Walk-through: In nums[0:2] = [NaN, inf], NaN outranks +inf to yield NaN. Once NaN exits, nums[1:3] = [inf, 10.0] yields inf, and once inf exits, nums[2:4] = [10.0, 20.0] yields 15.0.

Constraints

  • 1 <= k <= len(nums) <= 1,000,000
  • Elements are IEEE-754 floating-point values (32-bit float in C++, float in Python), including finite values, +inf, -inf, and NaN
  • Time complexity: O(n) where n = len(nums)
  • Auxiliary space complexity: O(1) beyond the returned output array/list

Step-by-step walkthrough

  1. Restate the precedence rules and complexity targets

    We are given an array nums of n floating-point numbers (1 <= k <= n <= 1,000,000) encoded in IEEE-754 (the universal hardware standard that defines binary floating-point numbers plus special values +inf, -inf, and NaN meaning "Not a Number"). We need to return n - k + 1 window means in O(n) time and O(1) extra memory, checking each window nums[s : s + k] in this exact priority order:

    Priority 1: at least one NaN present          ->  NaN
    Priority 2: both +inf and -inf present        ->  NaN   (because +inf + (-inf) is undefined)
    Priority 3: +inf present (no NaN, no -inf)    ->  +inf
    Priority 4: -inf present (no NaN, no +inf)    ->  -inf
    Priority 5: all k values are finite           ->  (sum of the k values) / k
    

    Because this coding sandbox executes Python, we build and test the exact algorithm in Python first and also provide the equivalent production C++17 implementation below.

  2. Why a naive running sum gets permanently poisoned

    Summing k elements from scratch for every window takes O(n * k) additions—around 2.5 * 10^11 operations when n = 1,000,000 and k = 500,000, which is far too slow.

    The textbook O(n) sliding-window shortcut maintains a single running sum (running_sum += entering - leaving). Unfortunately, IEEE-754 special values cannot be subtracted back out:

    running_sum = 3.0
    + NaN enters:  3.0 + NaN  = NaN
    - NaN leaves:  NaN - NaN  = NaN   <-- stuck as NaN forever!
    
    running_sum = 5.0
    + inf enters:  5.0 + inf  = inf
    - inf leaves:  inf - inf  = NaN   <-- also turns into NaN forever!
    

    Once a single NaN or inf touches running_sum, every future window outputs NaN even after the rest of the stream is completely clean. That is the poisoning bug forbidden by our eviction requirement.

  3. Separate exact integer counters from the finite sum

    To keep the floating-point sum clean, never add NaN, +inf, or -inf to the sum. Instead, track how many of each special value currently sit inside the window using three plain integers: nan_count, pos_inf_count, and neg_inf_count.

    When an element enters (direction = +1) we increment its counter; when it slides out (direction = -1) we decrement its counter. Because integer addition and subtraction are exact, each counter returns cleanly to 0 the instant the last special value exits! Only ordinary finite numbers are sent to the floating-point accumulator:

    import math
    
    
    class _WindowState:
        """Tracks special-value counts and a compensated finite sum for the active window."""
    
        def __init__(self) -> None:
            self.nan_count = 0
            self.pos_inf_count = 0
            self.neg_inf_count = 0
            self.total = 0.0
            self.comp = 0.0
    
        def add_finite(self, x: float) -> None:
            self.total += x  # upgraded to compensated addition in the next step
    
        def update(self, x: float, direction: int) -> None:
            """Update window state: `direction` is +1 when `x` enters and -1 when `x` leaves."""
            if math.isnan(x):
                self.nan_count += direction
            elif x == math.inf:
                self.pos_inf_count += direction
            elif x == -math.inf:
                self.neg_inf_count += direction
            else:
                self.add_finite(direction * x)
    
        def mean(self, k: int) -> float:
            """Evaluate the window mean following IEEE-754 precedence rules 1 through 5."""
            if self.nan_count > 0:
                return math.nan
            if self.pos_inf_count > 0 and self.neg_inf_count > 0:
                return math.nan
            if self.pos_inf_count > 0:
                return math.inf
            if self.neg_inf_count > 0:
                return -math.inf
            return (self.total + self.comp) / k
    
  4. Prevent precision loss with double precision and Neumaier summation

    Even when all values are finite, a naive running sum suffers two numerical bugs:

    1. Overflow and narrow precision in 32-bit float: Every floating-point format stores a fixed number of significant binary digits, called its significand (24 bits, or ~7 decimal digits, for C++ float; 53 bits, or ~16 decimal digits, for 64-bit double, which Python float uses natively). Summing 10^6 large finite float values near 3.4e38 overflows a 32-bit float to inf. Accumulating in 64-bit double prevents overflow completely because 10^6 * 3.4e38 = 3.4e44, far below double's ceiling of 1.8e308.
    2. Catastrophic cancellation: Catastrophic cancellation happens when adding a tiny number to a huge number rounds the tiny number away completely, so subtracting the huge number later leaves zero behind instead of the tiny number:
    Nums = [2^100, 1.0, 1.0], k = 2 (using plain 64-bit double):
      Window 0 [2^100, 1.0]:  2^100 + 1.0 rounds to 2^100  (the +1.0 is lost!)
      Slide to [1.0, 1.0]:    subtract 2^100 -> 0.0, then add 1.0 -> 1.0
      Computed mean = 1.0 / 2 = 0.5   (WRONG! True mean of [1.0, 1.0] is 1.0)
    

    We fix this with Neumaier's compensated summation, an improvement on Kahan summation that keeps a second double variable comp holding the low-order bits shaved off by rounding. Whenever we compute new_total = total + x, subtracting whichever input had the larger magnitude from new_total is guaranteed to have zero rounding error in IEEE-754 arithmetic; adding the smaller input back recovers the exact rounding error:

    Same example [2^100, 1.0, 1.0], k = 2 with Neumaier (total, comp):
      + 2^100 enters:  total = 2^100,  comp = 0.0
      + 1.0   enters:  new_total = 2^100;  error = (2^100 - 2^100) + 1.0 = +1.0  -> comp = 1.0
      - 2^100 leaves:  new_total = 0.0;    error = (2^100 - 0.0) - 2^100 =  0.0  -> total = 0.0, comp = 1.0
      + 1.0   enters:  new_total = 1.0;    error = (1.0 - 1.0) + 0.0     =  0.0  -> total = 1.0, comp = 1.0
      Mean = (total + comp) / 2 = (1.0 + 1.0) / 2 = 1.0   (EXACT!)
    
  5. Bound long-term drift by rebuilding every k slides

    Why isn't Neumaier compensation alone the end of the story? Because total and comp are two 53-bit doubles, together they hold roughly 106 bits of precision—not infinite precision. If an array contains three wildly separated scales like [2^120, 2^60, 1.0, 1.0, ...], 2^120 pushes 2^60 into comp, and 2^60 inside comp still rounds away 1.0!

    To guarantee that no past spike can corrupt the stream forever while keeping O(1) extra space, we recompute (total, comp) directly from the current window nums[start : start + k] once every k slides (start % k == 0):

    from typing import List
    
    
    def rebuild_example_loop(nums: List[float], k: int) -> int:
        """Count how many finite element reads all periodic rebuilds perform across n items."""
        # Rebuilds fire at start = k, 2k, 3k, ... — at most (n - k) // k times.
        # Each rebuild inspects k elements, totaling at most n - k reads overall: O(n)!
        work = 0
        for start in range(1, len(nums) - k + 1):
            if start % k == 0:
                work += k
        return work
    

    Because O(k) rebuild work happens only once every k windows, the amortized cost is at most one extra addition per element (O(n) total time and O(1) extra space), and rounding error can never accumulate across more than 3k operations.

  6. Walk through Example 2 step by step

    Let's trace nums = [5.0, inf, -inf, 2.0, 6.0] with k = 2 (and verify how NaN behaves in Example 3 as well):

    start  window         nan  +inf  -inf  total+comp  rebuild?  output  reason
    --------------------------------------------------------------------------------------------
    0      [5.0, inf]      0     1     0      5.0        no      +inf    only +inf     (Rule 3)
    1      [inf, -inf]     0     1     1      0.0        no       NaN    +inf and -inf (Rule 2)
    2      [-inf, 2.0]     0     0     1      2.0        yes     -inf    only -inf     (Rule 4)
    3      [2.0, 6.0]      0     0     0      8.0        no       4.0    8.0 / 2       (Rule 5)
    

    Notice how +inf and -inf each dominate while inside the window, cancel cleanly to 0 in their integer counters as soon as they leave, and leave window 3 ([2.0, 6.0] -> 4.0) completely uncorrupted. Likewise, in Example 3 ([NaN, inf, 10.0, 20.0], k = 2), nan_count = 1 in window 0 overrides pos_inf_count = 1 to emit NaN before recovering to inf and 15.0.

  7. Production C++17 implementation

    Here is the exact same O(n) time, O(1) auxiliary space algorithm written for the C++ signature. Input elements arrive as 32-bit float, finite sums accumulate in 64-bit double, and each window's mean is cast back to float:

    #include <cmath>
    #include <cstddef>
    #include <limits>
    #include <vector>
    
    struct WindowState {
        long long nan_count = 0;
        long long pos_inf_count = 0;
        long long neg_inf_count = 0;
        double total = 0.0;  // finite running sum in 64-bit double
        double comp = 0.0;   // Neumaier compensation for lost low-order bits
    
        void add_finite(double x) {
            double new_total = total + x;
            if (std::fabs(total) >= std::fabs(x)) {
                comp += (total - new_total) + x;
            } else {
                comp += (x - new_total) + total;
            }
            total = new_total;
        }
    
        void update(float v, int direction) {  // +1 on enter, -1 on exit
            if (std::isnan(v)) {
                nan_count += direction;
            } else if (std::isinf(v)) {
                if (v > 0) pos_inf_count += direction;
                else neg_inf_count += direction;
            } else {
                add_finite(direction * static_cast<double>(v));
            }
        }
    
        void rebuild_sum(const std::vector<float>& nums, std::size_t start, std::size_t end) {
            total = 0.0;
            comp = 0.0;
            for (std::size_t i = start; i < end; ++i) {
                if (std::isfinite(nums[i])) {
                    add_finite(static_cast<double>(nums[i]));
                }
            }
        }
    
        float mean(int k) const {
            if (nan_count > 0) return std::numeric_limits<float>::quiet_NaN();
            if (pos_inf_count > 0 && neg_inf_count > 0) return std::numeric_limits<float>::quiet_NaN();
            if (pos_inf_count > 0) return std::numeric_limits<float>::infinity();
            if (neg_inf_count > 0) return -std::numeric_limits<float>::infinity();
            return static_cast<float>((total + comp) / k);
        }
    };
    
    std::vector<float> sliding_window_mean(const std::vector<float>& nums, int k) {
        if (k <= 0 || static_cast<std::size_t>(k) > nums.size()) return {};
        const std::size_t n = nums.size();
        const std::size_t w = static_cast<std::size_t>(k);
    
        std::vector<float> result;
        result.reserve(n - w + 1);
    
        WindowState state;
        for (std::size_t i = 0; i < w; ++i) state.update(nums[i], +1);
        result.push_back(state.mean(k));
    
        for (std::size_t start = 1; start + w <= n; ++start) {
            state.update(nums[start - 1], -1);
            state.update(nums[start + w - 1], +1);
            if (start % w == 0) state.rebuild_sum(nums, start, start + w);
            result.push_back(state.mean(k));
        }
        return result;
    }
    

    Never compile this translation unit with -ffast-math or -Ofast: those flags let the compiler assume NaN and inf never occur and algebraically simplify (total - new_total) + x to 0.0, destroying both special-value checks and Neumaier compensation.

  8. Complete Python solution

    from typing import List
    import math
    
    
    class _WindowState:
        """Tracks special-value counts and a compensated finite sum for the active window."""
    
        def __init__(self) -> None:
            # Exact integer counts of non-finite IEEE-754 values currently inside the window.
            self.nan_count = 0
            self.pos_inf_count = 0
            self.neg_inf_count = 0
            # Neumaier compensated pair: (total + comp) approximates the exact finite sum.
            self.total = 0.0
            self.comp = 0.0
    
        def add_finite(self, x: float) -> None:
            """Add finite float `x` using Neumaier's compensated summation."""
            new_total = self.total + x
            # Subtract the larger-magnitude value from `new_total` first so that subtraction
            # is exact in IEEE-754 arithmetic, then add the smaller value to recover lost bits.
            if abs(self.total) >= abs(x):
                self.comp += (self.total - new_total) + x
            else:
                self.comp += (x - new_total) + self.total
            self.total = new_total
    
        def update(self, x: float, direction: int) -> None:
            """Update window state: `direction` is +1 when `x` enters and -1 when `x` leaves."""
            # Route non-finite values to integer counters so `total` is never poisoned by NaN/inf.
            if math.isnan(x):
                self.nan_count += direction
            elif x == math.inf:
                self.pos_inf_count += direction
            elif x == -math.inf:
                self.neg_inf_count += direction
            else:
                self.add_finite(direction * x)
    
        def rebuild_sum(self, nums: List[float], start: int, end: int) -> None:
            """Recompute the finite sum of nums[start:end] from scratch to clear old drift."""
            self.total = 0.0
            self.comp = 0.0
            for i in range(start, end):
                if math.isfinite(nums[i]):
                    self.add_finite(nums[i])
    
        def mean(self, k: int) -> float:
            """Evaluate the window mean following IEEE-754 precedence rules 1 through 5."""
            # Rule 1: any NaN dominates everything, including infinities.
            if self.nan_count > 0:
                return math.nan
            # Rule 2: (+inf) + (-inf) has an indeterminate sign, producing NaN.
            if self.pos_inf_count > 0 and self.neg_inf_count > 0:
                return math.nan
            # Rules 3 & 4: single-sided infinity dominates any finite sum.
            if self.pos_inf_count > 0:
                return math.inf
            if self.neg_inf_count > 0:
                return -math.inf
            # Rule 5: all k entries are finite, so return their compensated arithmetic mean.
            return (self.total + self.comp) / k
    
    
    def sliding_window_mean(nums: List[float], k: int) -> List[float]:
        """Return the mean of every contiguous window nums[s:s+k] in O(n) time and O(1) extra space."""
        n = len(nums)
        if k <= 0 or k > n:
            return []
    
        # Phase 1: populate the initial window nums[0:k].
        state = _WindowState()
        for i in range(k):
            state.update(nums[i], +1)
        result = [state.mean(k)]
    
        # Phase 2: slide one position at a time, evicting `nums[start - 1]` and adding `nums[start + k - 1]`.
        for start in range(1, n - k + 1):
            state.update(nums[start - 1], -1)
            state.update(nums[start + k - 1], +1)
            # Every k slides, rebuild the finite sum in O(k) time (amortized O(1) per slide)
            # so rounding error can never accumulate across more than ~3k additions.
            if start % k == 0:
                state.rebuild_sum(nums, start, start + k)
            result.append(state.mean(k))
        return result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine tracking the average weight of boxes currently riding on a 2-slot conveyor belt while occasional "BROKEN SENSOR" (NaN), "OVERLOAD+" (+inf), and "UNDERFLOW-" (-inf) tags pass through. If you type "BROKEN SENSOR" into a pocket calculator's running total, the display locks onto ERROR forever even after that bad box drops off the belt; instead, you click three separate integer tally counters for the special tags and only feed ordinary finite weights into your calculator.

Both obvious baselines fail in production. Re-summing all k elements from scratch at every step takes O(n * k) work, which stalls on million-element streams, while a naive sum += enter - leave running total turns permanently into NaN the first time NaN or inf is subtracted (NaN - NaN = NaN and inf - inf = NaN). Even on purely finite data, adding a huge spike to a plain float sum rounds away small neighbors (catastrophic cancellation—losing small values completely when added to and later subtracted from a much larger number), so we combine 64-bit double Neumaier compensated summation (tracking lost rounding bits in a second variable comp) with a periodic O(k) rebuild every k slides.

Walk through Example 2 (nums = [5.0, inf, -inf, 2.0, 6.0], k = 2): - Window 0 [5.0, inf]: pos_inf_count = 1, finite sum = 5.0 -> pos_inf_count == 1 outputs +inf. - Window 1 [inf, -inf]: 5.0 exits (finite sum = 0.0), -inf enters (neg_inf_count = 1) -> both infinity counters are positive, outputting NaN. - Window 2 [-inf, 2.0]: +inf exits (pos_inf_count = 0), 2.0 enters (finite sum = 2.0) -> neg_inf_count == 1 outputs -inf. - Window 3 [2.0, 6.0]: -inf exits (neg_inf_count = 0), 6.0 enters (finite sum = 8.0) -> all special counters are 0, outputting 8.0 / 2 = 4.0 with zero poisoning!

Complexity

  • Time: O(n). Every element enters the window at most once and exits at most once, doing O(1) counter or arithmetic work per step (~2n updates). Rebuilding the finite sum touches k elements once every k slides (start = k, 2k, 3k, ...), adding at most n - k element reads across the entire run, so total work stays strictly below 3n constant-time operations.
  • Space: O(1) auxiliary space beyond the returned output list of length n - k + 1. _WindowState stores only three integers (nan_count, pos_inf_count, neg_inf_count) and two 64-bit floats (total, comp), and rebuild_sum reads nums in place without allocating buffers.

Edge cases

  • k = 1 and k = n: k = 1 outputs a copy of each element's IEEE-754 value; k = n outputs a single 1-element list without entering the sliding loop.
  • NaN mixed with +inf or -inf: nan_count > 0 is checked first, so NaN always wins (as in Example 3's [NaN, inf] -> NaN).
  • +inf and -inf in the same window: Both counters are positive, returning NaN even when finite numbers are also inside the window.
  • Large finite 32-bit floats near FLT_MAX (~3.4e38): Summing up to 10^6 such values reaches ~3.4e44, which would overflow a 32-bit float to inf but fits comfortably inside a 64-bit double (<= 1.8e308) before dividing by k.
  • Subnormal floats: Subnormal floats (tiny numbers smaller than 2^-126 down to 2^-149 that trade leading precision bits to represent values very close to zero) convert to normal 64-bit double values with zero loss of bits.
  • Extreme multi-scale finite spikes: Because (total, comp) carries ~106 bits of precision (two 53-bit doubles), three simultaneous scales separated by more than 2^106 (such as 2^120, 2^60, and 1.0) can still drop 1.0 until the next start % k == 0 rebuild wipes out the error within at most k windows.

Common mistakes

  • Putting NaN or +/-inf into the floating-point running sum, permanently poisoning all subsequent windows with NaN.
  • Checking x == float("nan") instead of math.isnan(x) or std::isnan(x)—by IEEE-754 definition, NaN == NaN always evaluates to False.
  • Returning +inf or -inf when both +inf and -inf sit inside the window at the same time instead of returning NaN.
  • Accumulating finite values in 32-bit float rather than 64-bit double, causing premature overflow on large finite inputs and severe rounding drift on long arrays.
  • Using basic Kahan summation instead of Neumaier summation: standard Kahan fails when the incoming value x has a larger magnitude than the current total (such as total = 1.0 followed by x = 2^100), whereas Neumaier's abs(total) >= abs(x) branch handles both orders symmetrically.
  • Forgetting to decrement nan_count, pos_inf_count, or neg_inf_count when elements slide out of the left edge of the window.

Alternative approaches

  • Recompute every window with math.fsum: Evaluates each window independently with exact rounding, but takes O(n * k) time, violating the O(n) constraint for large k.
  • Two-stack subtraction-free sliding window: A two-stack queue (maintaining a front stack and back stack of partial finite sums so every window sum is computed by adding front_sum + back_sum with zero floating-point subtractions) completely prevents departed huge spikes from canceling current small numbers and still runs in amortized O(n) time, but uses O(k) auxiliary memory instead of O(1).
  • Exact 320-bit fixed-point integer accumulator: Scaling every finite float32 into an exact integer multiple of 2^-149 gives zero drift with O(1) extra space and no periodic rebuilds, at the cost of a small 5-word (5 x uint64_t) integer helper in C++.

Follow-up questions

  • Why do aggressive compiler flags such as -ffast-math or -Ofast break IEEE-754 predicates and compensated summation, and how do you protect this code in production? -ffast-math (which -Ofast enables alongside -O3) turns on -ffinite-math-only—allowing the compiler to optimize under the assumption that NaN and inf never exist at runtime, folding std::isnan(x) to false and treating returned quiet_NaN() / infinity() constants as undefined—and -fassociative-math, which lets the optimizer rewrite (total - new_total) + x to 0.0, silently deleting Neumaier compensation! To safeguard production C++ code, isolate this module in a translation unit compiled without fast-math (or pass -fno-finite-math-only -fno-associative-math), inspect input bit patterns directly via std::memcpy into uint32_t (exponent bits 0x7F800000 all 1s with non-zero mantissa for NaN, zero mantissa for inf), static_assert(std::numeric_limits<float>::is_iec559), and run unit tests containing NaN, +/-inf, and [2^100, 1.0, 1.0] under exact release compiler flags in CI.
  • Suppose the stream exceeds 10^9 elements spanning extreme magnitude gaps—how can you eliminate subtraction drift in O(1) space without ever rescanning the window? Use an exact fixed-point representation—converting every finite float32 into an exact integer multiple of the smallest possible subnormal unit 2^-149. Because every finite float32 has magnitude < 2^128 and spacing >= 2^-149, multiplying x by 2^149 yields an exact integer < 2^277; summing up to 2^42 (~4.4 * 10^12) elements stays < 2^319, which fits with a sign bit inside five 64-bit integers (320 bits = 40 bytes, O(1) space!). Because integer + and - have zero rounding error, the running sum never drifts over billions or trillions of updates without ever resetting or rereading past elements (in Python, int is already arbitrary-precision: scale by 2**149 via x.as_integer_ratio() and divide total_fixed / (k << 149) once per window).
  • How would you redesign the window state if windows were defined over a trailing time interval and live events could arrive out of timestamp order? Because integer special-value counts and exact fixed-point sums are commutative and invertible (addition order does not change the result), a window (t - W, t] only depends on which events fall inside its time range. Store active events in a timestamp-ordered min-heap or ring buffer of fine time buckets (say, 1 ms sub-aggregates holding their own counts and sums) so expired entries evict cleanly as t advances, and divide by the dynamic window event count m (0 / 0 -> NaN when empty). To handle out-of-order network arrivals, hold back window emission using a watermark—a progress timestamp max_seen_event_time - allowed_lateness—emitting the mean for time t once the watermark passes t, while routing rarer ultra-late events to a correction stream or dead-letter queue.

Follow-up questions

Similar questions

More Headlands interview questions

All 4 Headlands questions →