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^6opis associative over integers
Step-by-step walkthrough
Restate the problem and reconcile `op`'s input format
Given an array
numsof lengthn, a window sizek(1 <= k <= n <= 10^5), and a two-argument operationop, we need to return an array of lengthn - k + 1where indexiholds the reduction of the windownums[i : i + k]from left to right.Two key properties shape our design: -
opis 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 (becauseopmight not be commutative, i.e.,a op bis not guaranteed to equalb op a). - String name vs. callable:opmay 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.Why recomputing every window or "undoing" the leaving element fails
A naive loop folds all
kelements from scratch for each of then - k + 1windows. That performs(n - k + 1) * (k - 1)calls toop— around2.5 * 10^9operations whenn = 100,000andk = 50,000, which times out because consecutive windows sharek - 1identical 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 a0enters the window[3, 0, 4], the running product becomes0. When0later leaves the window, you cannot divide0 / 0to recover the remaining product! - Bitwise AND (
bitwise_and): Once a bit is cleared to0, you cannot tell how many elements inside the window had a0in that bit. For instance,[12, 10, 6]and[12, 10, 4]both have AND equal to0, yet removing12and appending15yields10 & 6 & 15 = 2for the first window and10 & 4 & 15 = 0for the second.
We need a data structure that only ever combines elements forward and never tries to undo them.
- Multiplication (
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 isO(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): Appendvaluetoback_valuesand updateback_total = combine(back_total, value)(valueis newer, so it goes on the right). 2.pop(): Pop the top offront_totals. Iffront_totalsis empty, first pour all ofback_valuesintofront_totalsfrom newest to oldest, accumulatingrunning_total = combine(value, running_total)(valueis older than everything already moved, so it goes on the left!). Now the oldest item sits atfront_totals[-1]and every slot stores the exact suffix reduction up to the boundary. 3.total(): Combinefront_totals[-1]withback_total(or return whichever side is non-empty).Every array element is pushed into
back_valuesonce, poured intofront_totalsat most once, and popped at most once — at most 3 calls toopper element across the entire run (O(n)total time)!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]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 (0foradd,1formultiply,-1forbitwise_and,-infinityformax), we checkif not self.back_values:andif not self.front_totals:so every reduction starts directly from a real window element. - Left-to-right operand order: Inpush,valueis newer (combine(self.back_total, value)). In_move_back_to_front,valueis older (combine(value, running_total)). Intotal,front_totalsis 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)Slide the window and trace Example 3 (`bitwise_and`)
Now
sliding_window_reducesweepsiacrossnums: 1. Pushnums[i]. 2. Ifi >= k, the window temporarily hask + 1elements, so popnums[i - k]. 3. Ifi >= k - 1, the window has reached full sizek, so appendwindow.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 resultLet'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]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 toop(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 ontoback_values, moved and combined at most once intofront_totals, and combined at most once intotal(), totaling at most3ncalls toop. (Note: for'multiply'with largek, Python big integers can grow toO(k)digits, making big-integer multiplication scale with digit count rather than machine-wordO(1).) - Space:
O(k)extra space excluding the output list of lengthn - k + 1. At any momentfront_totalsandback_valuestogether hold at mostk + 1elements (right beforepop()runs).
Edge cases
- Window of size
1(k = 1): Each element entersback_values, becomes the window total, and is evicted on the next step, returning a copy ofnums. - Single full-array window (
k == len(nums)):window.pop()never triggers (i < kthroughout), andwindow.total()runs once ati = n - 1, returning a one-element list. - Zeros with
'multiply': Because values are only ever multiplied forward and never divided out, windows after a0leaves 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 leading1bits, so-1 & x == x), whichoperator.and_handles natively. - Callable
opvs. string name:get_combineaccepts both'add'-style strings andlambda a, b: ...functions, raisingValueErroron unknown string names.
Common mistakes
- Dividing by
nums[i - k]to slide'multiply': A single0insidenumsraisesZeroDivisionError, and using floating-point/loses integer precision on products above2^53. - Initializing totals to a hardcoded
0or1: Startingrunning_totalat0breaks'multiply','bitwise_and'(0 & x == 0), and'max'on negative arrays (max(0, -5) == 0). Checkingif not self.back_values:/running_total is Noneavoids needing an identity element altogether. - Reversing operand order during
_move_back_to_front: Writingself.combine(running_total, value)instead ofself.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 index0shiftskelements every step, degrading runtime right back toO(n * k).
Alternative approaches
- Monotonic deque (
max/minonly): 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-windowmaxormininO(n)time andO(k)space, though it does not generalize toadd,multiply, orbitwise_and. - Block prefix/suffix arrays (
O(n)worst-case, no stacks): Partitionnumsinto contiguous blocks of lengthk, precompute block prefixes and suffixes, and answer each windownums[i : i + k]as either a single block prefix (wheni % k == 0) orsuffix[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
TwoStackWindownever attempts to undo or invert an outgoing value — it only combines elements forward usingop— non-invertible associative operations likebitwise_and,bitwise_or,max, andminalready run inO(n)time out of the box. As specialized alternatives,max/mincan also use a monotonic deque inO(n)time, andbitwise_and/bitwise_oron boundedB-bit integers can maintain per-bit ones-counts across the window inO(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?
TwoStackWindowusesO(k)extra space becausefront_totalsandback_valueshold up tok + 1entries at once. To achieveO(1)extra space for any associativeopwithout mutatingnums, use the output listresult(of lengthn - k + 1) as scratch storage with block boundaries at multiplesbofk: every window[i, i + k - 1]contains a unique multiplebofk. For each boundaryb, sweepibackward fromb - 1down tomax(0, b - k + 1)keeping one scalarsuffixand storingresult[i] = suffixwheneveri <= n - k; then sweepjforward frombtomin(b + k - 1, n - 1)keeping one scalarprefixand settingresult[j - k + 1]toprefix(ifj - k + 1 == b) orcombine(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; whenopis non-commutative (such as 2x2 matrix multiplication or string concatenation), we must preserve strict left-to-right arrival order in everycombinecall while still regrouping freely via associativity.TwoStackWindowalready guarantees this:pushplaces the newer element on the right (combine(back_total, value)),_move_back_to_frontplaces the older element on the left (combine(value, running_total)), andtotalplaces the olderfront_totals[-1]on the left ofback_total(combine(front_totals[-1], back_total)).
Follow-up questions
- Does the algorithm need any changes when the binary operation cannot be inverted, such as bitwise OR or range minimum?
- 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?
- What adjustments are required if the associative operation is not commutative, such as matrix multiplication?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array