Associative Reduction Across Sliding Windows

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You are given an integer list nums, a window width k, and an associative binary operator op. Compute a list of length len(nums) - k + 1 in which entry i (0 <= i <= len(nums) - k) equals the left-to-right fold of the contiguous slice nums[i : i + k] under op:

(((nums[i] op nums[i + 1]) op nums[i + 2]) ... op nums[i + k - 1])

Because op is associative ((x op y) op z == x op (y op z)), grouping parentheses in any tree order is valid as long as operand left-to-right arrival order is preserved (commutativity is not guaranteed). When k == 1, each single-element window reduces to nums[i] itself; if nums is empty or k falls outside [1, len(nums)], return [].

op may be provided either as one of the supported operation strings ("add", "multiply", "bitwise_and", "bitwise_or", "bitwise_xor", "max", "min") or as a two-argument Python callable op(a, b) -> int.

Implement:

def sliding_window_reduce(nums: List[int], k: int, op: str) -> List[int]:

Examples

Example 1

Input:  nums = [4, -1, 6, 2, -3], k = 3, op = "add"
Output: [9, 7, 5]

Walk-through: - Window [4, -1, 6] sums to 9. - Window [-1, 6, 2] sums to 7. - Window [6, 2, -3] sums to 5.

Example 2

Input:  nums = [5, -2, 0, 3, 4], k = 2, op = "multiply"
Output: [-10, 0, 0, 12]

Walk-through: - Consecutive size-2 products are 5 * (-2) = -10, (-2) * 0 = 0, 0 * 3 = 0, and 3 * 4 = 12 (notice that once 0 leaves the window, [3, 4] recovers 12).

Example 3

Input:  nums = [14, 6, 7, 13], k = 3, op = "bitwise_and"
Output: [6, 4]

Walk-through: - In binary, 14 = 1110, 6 = 0110, 7 = 0111, and 13 = 1101. - First window: 14 & 6 & 7 = 6 (0110). - Second window: 6 & 7 & 13 = 4 (0100).

Constraints

  • 1 <= k <= len(nums) <= 10^5
  • -10^6 <= nums[i] <= 10^6
  • op is associative over integers

Step-by-step walkthrough

  1. Restate the problem and reconcile `op`'s input format

    Given an array nums of length n, a window size k (1 <= k <= n <= 10^5), and a two-argument operation op, we need to return an array of length n - k + 1 where index i holds the reduction of the window nums[i : i + k] from left to right.

    Two key properties shape our design: - op is associative: (a op b) op c == a op (b op c). We are allowed to place parentheses however we like, as long as we keep elements in left-to-right order (because op might not be commutative, i.e., a op b is not guaranteed to equal b op a). - String name vs. callable: op may be passed either as an operation name string ('add', 'multiply', 'bitwise_and', etc.) or directly as a two-argument Python callable. Supporting both takes a tiny lookup helper.

  2. Why recomputing every window or "undoing" the leaving element fails

    A naive loop folds all k elements from scratch for each of the n - k + 1 windows. That performs (n - k + 1) * (k - 1) calls to op — around 2.5 * 10^9 operations when n = 100,000 and k = 50,000, which times out because consecutive windows share k - 1 identical elements.

    For addition, you can slide a window in O(1) by adding the entering number and subtracting the leaving number. Why doesn't that trick work in general? Because it requires an inverse operation, and two of our three sample operations do not have one:

    • Multiplication (multiply): If a 0 enters the window [3, 0, 4], the running product becomes 0. When 0 later leaves the window, you cannot divide 0 / 0 to recover the remaining product!
    • Bitwise AND (bitwise_and): Once a bit is cleared to 0, you cannot tell how many elements inside the window had a 0 in that bit. For instance, [12, 10, 6] and [12, 10, 4] both have AND equal to 0, yet removing 12 and appending 15 yields 10 & 6 & 15 = 2 for the first window and 10 & 4 & 15 = 0 for the second.

    We need a data structure that only ever combines elements forward and never tries to undo them.

  3. Key idea: turn two stacks into a sliding-window queue

    A stack makes prefix/suffix reductions effortless: if each stack slot remembers the reduction of itself with everything pushed earlier, reading the whole stack's reduction is O(1) and popping is O(1). A sliding window, however, is a First-In, First-Out queue (new items enter on the right, oldest items leave on the left).

    We can build a queue out of two stacks placed back-to-back:

    Window elements (oldest -> newest):   [ x0,  x1,  x2  |  x3,  x4 ]
                                          <-- front_totals | back_values -->
                                           (older half:     (newer half:
                                            x0 is on top,    append on right,
                                            ready to pop)    track back_total
                                                             = x3 op x4)
    
    Whole window reduction = front_totals[-1]  op  back_total
                           = (x0 op x1 op x2)  op  (x3 op x4)
    

    How each operation works: 1. push(value): Append value to back_values and update back_total = combine(back_total, value) (value is newer, so it goes on the right). 2. pop(): Pop the top of front_totals. If front_totals is empty, first pour all of back_values into front_totals from newest to oldest, accumulating running_total = combine(value, running_total) (value is older than everything already moved, so it goes on the left!). Now the oldest item sits at front_totals[-1] and every slot stores the exact suffix reduction up to the boundary. 3. total(): Combine front_totals[-1] with back_total (or return whichever side is non-empty).

    Every array element is pushed into back_values once, poured into front_totals at most once, and popped at most once — at most 3 calls to op per element across the entire run (O(n) total time)!

  4. Resolve `op` from either a string name or a callable

    Let's first write get_combine(op) so both callable functions and string names like 'add', 'multiply', and 'bitwise_and' resolve cleanly to a two-argument Python function.

    import operator
    
    # Map operation names used by the judge to standard two-argument functions.
    OPERATIONS = {
        "add": operator.add,
        "multiply": operator.mul,
        "bitwise_and": operator.and_,
        "bitwise_or": operator.or_,
        "bitwise_xor": operator.xor,
        "max": max,
        "min": min,
    }
    
    
    def get_combine(op):
        """Return a two-argument callable for `op` (accepting either a function or a string name)."""
        if callable(op):
            return op
        if op not in OPERATIONS:
            raise ValueError(f"unknown operation: {op}")
        return OPERATIONS[op]
    
  5. Implement `TwoStackWindow` while preserving left-to-right order

    Pay close attention to two details in TwoStackWindow: - No identity element needed: Instead of guessing an identity value (0 for add, 1 for multiply, -1 for bitwise_and, -infinity for max), we check if not self.back_values: and if not self.front_totals: so every reduction starts directly from a real window element. - Left-to-right operand order: In push, value is newer (combine(self.back_total, value)). In _move_back_to_front, value is older (combine(value, running_total)). In total, front_totals is older (combine(self.front_totals[-1], self.back_total)). That guarantees correctness even for non-commutative operations!

    class TwoStackWindow:
        """A FIFO sliding-window queue that reduces elements oldest-to-newest without needing an inverse."""
    
        def __init__(self, combine):
            self.combine = combine
            # front_totals: older half of the window, with the oldest element at front_totals[-1].
            # Each entry stores the left-to-right reduction from that element through front_totals[0].
            self.front_totals = []
            # back_values: newer half of the window in arrival order [oldest_in_back, ..., newest].
            self.back_values = []
            # back_total: running left-to-right reduction of all items currently in back_values.
            self.back_total = None
    
        def push(self, value: int) -> None:
            # New arrivals sit to the right of everything already in back_values.
            if not self.back_values:
                self.back_total = value
            else:
                self.back_total = self.combine(self.back_total, value)
            self.back_values.append(value)
    
        def pop(self) -> None:
            # Remove the oldest element in the window; refill front_totals from back_values when empty.
            if not self.front_totals:
                self._move_back_to_front()
            self.front_totals.pop()
    
        def _move_back_to_front(self) -> None:
            # Pop back_values from newest to oldest so the oldest element lands on top of front_totals.
            running_total = None
            while self.back_values:
                value = self.back_values.pop()
                if running_total is None:
                    running_total = value
                else:
                    # `value` arrived earlier than everything in `running_total`, so `value` goes on the left.
                    running_total = self.combine(value, running_total)
                self.front_totals.append(running_total)
            self.back_total = None
    
        def total(self) -> int:
            # Everything in front_totals arrived earlier than everything in back_values.
            if not self.front_totals:
                return self.back_total
            if not self.back_values:
                return self.front_totals[-1]
            return self.combine(self.front_totals[-1], self.back_total)
    
  6. Slide the window and trace Example 3 (`bitwise_and`)

    Now sliding_window_reduce sweeps i across nums: 1. Push nums[i]. 2. If i >= k, the window temporarily has k + 1 elements, so pop nums[i - k]. 3. If i >= k - 1, the window has reached full size k, so append window.total().

    from typing import List
    
    
    def sliding_window_reduce(nums: List[int], k: int, op: str) -> List[int]:
        if not nums or k <= 0 or k > len(nums):
            return []
    
        combine = get_combine(op)
        window = TwoStackWindow(combine)
        result = []
    
        for i in range(len(nums)):
            # Phase 1: Add the newly entering right-edge element nums[i].
            window.push(nums[i])
    
            # Phase 2: Once more than k elements are inside (i >= k), evict outgoing nums[i - k].
            if i >= k:
                window.pop()
    
            # Phase 3: Starting at i = k - 1, the window holds exactly k elements, so record its total.
            if i >= k - 1:
                result.append(window.total())
    
        return result
    

    Let's trace Example 3 (nums = [14, 6, 7, 13], k = 3, op = 'bitwise_and'; in binary: 14 = 1110, 6 = 0110, 7 = 0111, 13 = 1101):

    i = 0 (push 14):  front_totals = []               back_values = [14],        back_total = 14
    i = 1 (push 6):   front_totals = []               back_values = [14, 6],     back_total = 14 & 6 = 6
    i = 2 (push 7):   front_totals = []               back_values = [14, 6, 7],  back_total = 6 & 7 = 6
          i >= 2 -> record total(): front_totals is empty -> append 6
    
    i = 3 (push 13):  back_values = [14, 6, 7, 13], back_total = 6 & 13 = 4
          i >= 3 -> pop(): front_totals is empty, so _move_back_to_front() pours newest-first:
            pop 13 -> running_total = 13              -> front_totals = [13]
            pop 7  -> running_total = 7 & 13 = 5      -> front_totals = [13, 5]
            pop 6  -> running_total = 6 & 5  = 4      -> front_totals = [13, 5, 4]
            pop 14 -> running_total = 14 & 4 = 4      -> front_totals = [13, 5, 4, 4]
          back_values = [], back_total = None
          front_totals.pop() removes top 4 (for outgoing 14) -> front_totals = [13, 5, 4]
          i >= 2 -> record total(): back_values is empty -> front_totals[-1] = 4 -> append 4
    
    Final result: [6, 4]
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import operator
    
    # Map operation names used by the judge to standard two-argument functions.
    OPERATIONS = {
        "add": operator.add,
        "multiply": operator.mul,
        "bitwise_and": operator.and_,
        "bitwise_or": operator.or_,
        "bitwise_xor": operator.xor,
        "max": max,
        "min": min,
    }
    
    
    def get_combine(op):
        """Return a two-argument callable for `op` (accepting either a function or a string name)."""
        if callable(op):
            return op
        if op not in OPERATIONS:
            raise ValueError(f"unknown operation: {op}")
        return OPERATIONS[op]
    
    
    class TwoStackWindow:
        """A FIFO sliding-window queue that reduces elements oldest-to-newest without needing an inverse."""
    
        def __init__(self, combine):
            self.combine = combine
            # front_totals: older half of the window, with the oldest element at front_totals[-1].
            # Each entry stores the left-to-right reduction from that element through front_totals[0].
            self.front_totals = []
            # back_values: newer half of the window in arrival order [oldest_in_back, ..., newest].
            self.back_values = []
            # back_total: running left-to-right reduction of all items currently in back_values.
            self.back_total = None
    
        def push(self, value: int) -> None:
            # New arrivals sit to the right of everything already in back_values.
            if not self.back_values:
                self.back_total = value
            else:
                self.back_total = self.combine(self.back_total, value)
            self.back_values.append(value)
    
        def pop(self) -> None:
            # Remove the oldest element in the window; refill front_totals from back_values when empty.
            if not self.front_totals:
                self._move_back_to_front()
            self.front_totals.pop()
    
        def _move_back_to_front(self) -> None:
            # Pop back_values from newest to oldest so the oldest element lands on top of front_totals.
            running_total = None
            while self.back_values:
                value = self.back_values.pop()
                if running_total is None:
                    running_total = value
                else:
                    # `value` arrived earlier than everything in `running_total`, so `value` goes on the left.
                    running_total = self.combine(value, running_total)
                self.front_totals.append(running_total)
            self.back_total = None
    
        def total(self) -> int:
            # Everything in front_totals arrived earlier than everything in back_values.
            if not self.front_totals:
                return self.back_total
            if not self.back_values:
                return self.front_totals[-1]
            return self.combine(self.front_totals[-1], self.back_total)
    
    
    def sliding_window_reduce(nums: List[int], k: int, op: str) -> List[int]:
        if not nums or k <= 0 or k > len(nums):
            return []
    
        combine = get_combine(op)
        window = TwoStackWindow(combine)
        result = []
    
        for i in range(len(nums)):
            # Phase 1: Add the newly entering right-edge element nums[i].
            window.push(nums[i])
    
            # Phase 2: Once more than k elements are inside (i >= k), evict outgoing nums[i - k].
            if i >= k:
                window.pop()
    
            # Phase 3: Starting at i = k - 1, the window holds exactly k elements, so record its total.
            if i >= k - 1:
                result.append(window.total())
    
        return result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a single stack of trays where each tray has written on it the combined result of itself and every tray underneath it: reading the whole stack's result just looks at the top tray, and lifting the top tray off immediately exposes the exact result of everything underneath — no "undo" button needed! A sliding window, however, acts like a conveyor belt (a FIFO queue, meaning First-In, First-Out: new elements enter on the right and the oldest elements leave from the left). By placing two stacks back-to-back — an inbox stack (back_values) catching new arrivals on the right and an outbox stack (front_totals) dispensing the oldest items on the left — we simulate a conveyor belt that computes any associative operation (an operation where (a op b) op c == a op (b op c), meaning parenthesizing doesn't change the result) without ever dividing or subtracting!

Why do simpler approaches fail? Recomputing all k elements from scratch for each window takes O(n * k) operations, reaching billions of steps when n = 100,000 and k = 50,000. Trying to slide in O(1) by "undoing" the outgoing element fails whenever op lacks an inverse operation (a reverse operation that recovers the prior value): multiplying by 0 wipes out the product of the other k - 1 numbers so you cannot divide by 0 when it leaves, and bitwise_and clears 0 bits permanently without recording how many elements cleared them.

Watch how the two stacks handle Example 2 (nums = [5, -2, 0, 3, 4], k = 2, op = 'multiply') cleanly across a zero without ever dividing:

i = 0 (push 5):  front = []          back = [5], back_total = 5
i = 1 (push -2): front = []          back = [5, -2], back_total = -10  -> window [5, -2] outputs -10
i = 2 (push 0):  back = [5, -2, 0] -> pop pours newest-first into front:
                   0 -> 0,  -2 -> -2*0 = 0,  5 -> 5*0 = 0  => front = [0, 0, 0], back = []
                 pop removes 5's entry -> front = [0, 0]               -> window [-2, 0] outputs 0
i = 3 (push 3):  back = [3], back_total = 3
                 pop removes -2's entry -> front = [0]                 -> window [0, 3] outputs 0*3 = 0
i = 4 (push 4):  back = [3, 4], back_total = 12
                 pop removes 0's entry -> front = []                   -> window [3, 4] outputs 12!

Complexity

Let n = len(nums) and k be the window size.

  • Time: O(n) calls to op (O(1) amortized per window). Amortized time means the average cost per step over the entire sequence of operations is constant, even if an occasional step does extra work. Every element is combined at most once when pushed onto back_values, moved and combined at most once into front_totals, and combined at most once in total(), totaling at most 3n calls to op. (Note: for 'multiply' with large k, Python big integers can grow to O(k) digits, making big-integer multiplication scale with digit count rather than machine-word O(1).)
  • Space: O(k) extra space excluding the output list of length n - k + 1. At any moment front_totals and back_values together hold at most k + 1 elements (right before pop() runs).

Edge cases

  • Window of size 1 (k = 1): Each element enters back_values, becomes the window total, and is evicted on the next step, returning a copy of nums.
  • Single full-array window (k == len(nums)): window.pop() never triggers (i < k throughout), and window.total() runs once at i = n - 1, returning a one-element list.
  • Zeros with 'multiply': Because values are only ever multiplied forward and never divided out, windows after a 0 leaves immediately recover the exact product of the remaining non-zero elements.
  • Negative integers with 'bitwise_and': Python represents negative integers using infinite-width two's complement (a binary representation where negative numbers behave as if they have infinitely many leading 1 bits, so -1 & x == x), which operator.and_ handles natively.
  • Callable op vs. string name: get_combine accepts both 'add'-style strings and lambda a, b: ... functions, raising ValueError on unknown string names.

Common mistakes

  • Dividing by nums[i - k] to slide 'multiply': A single 0 inside nums raises ZeroDivisionError, and using floating-point / loses integer precision on products above 2^53.
  • Initializing totals to a hardcoded 0 or 1: Starting running_total at 0 breaks 'multiply', 'bitwise_and' (0 & x == 0), and 'max' on negative arrays (max(0, -5) == 0). Checking if not self.back_values: / running_total is None avoids needing an identity element altogether.
  • Reversing operand order during _move_back_to_front: Writing self.combine(running_total, value) instead of self.combine(value, running_total) silently passes commutative tests (+, *, &) and fails on non-commutative associative operations like matrix multiplication or string/digit concatenation.
  • Using list.pop(0) to maintain a queue: Removing index 0 shifts k elements every step, degrading runtime right back to O(n * k).

Alternative approaches

  • Monotonic deque (max / min only): A monotonic deque (a double-ended queue whose stored elements are kept in strictly sorted order by dropping dominated elements from the back) solves sliding-window max or min in O(n) time and O(k) space, though it does not generalize to add, multiply, or bitwise_and.
  • Block prefix/suffix arrays (O(n) worst-case, no stacks): Partition nums into contiguous blocks of length k, precompute block prefixes and suffixes, and answer each window nums[i : i + k] as either a single block prefix (when i % k == 0) or suffix[i] op prefix[i + k - 1].

Follow-up questions

  • Does the algorithm need any changes when the binary operation cannot be inverted, such as bitwise OR or range minimum? Nothing in our two-stack queue needs to change! Because TwoStackWindow never attempts to undo or invert an outgoing value — it only combines elements forward using op — non-invertible associative operations like bitwise_and, bitwise_or, max, and min already run in O(n) time out of the box. As specialized alternatives, max/min can also use a monotonic deque in O(n) time, and bitwise_and/bitwise_or on bounded B-bit integers can maintain per-bit ones-counts across the window in O(n * B) time.
  • How much auxiliary memory does the two-stack window require, and how could you reduce extra working space to O(1) outside the returned list? TwoStackWindow uses O(k) extra space because front_totals and back_values hold up to k + 1 entries at once. To achieve O(1) extra space for any associative op without mutating nums, use the output list result (of length n - k + 1) as scratch storage with block boundaries at multiples b of k: every window [i, i + k - 1] contains a unique multiple b of k. For each boundary b, sweep i backward from b - 1 down to max(0, b - k + 1) keeping one scalar suffix and storing result[i] = suffix whenever i <= n - k; then sweep j forward from b to min(b + k - 1, n - 1) keeping one scalar prefix and setting result[j - k + 1] to prefix (if j - k + 1 == b) or combine(result[j - k + 1], prefix) otherwise.
  • What adjustments are required if the associative operation is not commutative, such as matrix multiplication? An operation is commutative when a op b == b op a; when op is non-commutative (such as 2x2 matrix multiplication or string concatenation), we must preserve strict left-to-right arrival order in every combine call while still regrouping freely via associativity. TwoStackWindow already guarantees this: push places the newer element on the right (combine(back_total, value)), _move_back_to_front places the older element on the left (combine(value, running_total)), and total places the older front_totals[-1] on the left of back_total (combine(front_totals[-1], back_total)).

Follow-up questions

Similar questions

More Vmware interview questions

All 1 Vmware questions →