Fixed-Width Window Folds with Add, Multiply, or AND
Stacks & QueuesAuto-graded · 21 test casesLast updated
Compute the fold of every length-k window of an array under a named associative operation, ideally in linear time without relying on inverse operations.
You are given a list of integers values, a window length k, and the name of an operation operation. The operation is one of three strings:
"add": ordinary integer addition"multiply": ordinary integer multiplication"bitwise_and": bitwise AND (&)
Consider every contiguous block of exactly k elements in values, starting from the leftmost block and moving one position right each time. For each block, combine its elements from left to right using the named operation, and report the result.
Return a list of these results, one per block, in order of the block's starting position. The list has len(values) - k + 1 entries.
If operation is not one of the three allowed names, raise a ValueError.
A direct recomputation of each block can be too slow for the largest inputs, so aim for a solution that does roughly constant amortized work per step and does not depend on the operation having an inverse (for example, division fails when a block contains zero, and AND cannot be undone).
Constraints
1 <= k <= len(values) <= 10^5- Each element of
valuesis an integer in[-10^6, 10^6] operationis one of"add","multiply","bitwise_and"- Negative numbers use standard two's-complement semantics for
"bitwise_and"(as in Python's&) - When
k = 1, the result equals the input list - When
k = len(values), the result has exactly one element - Products may be very large; Python's arbitrary-precision integers are acceptable
Examples
Example 1
Input: window_fold([1, 2, 3, 4, 5], 3, 'add')
Output: [6, 9, 12]
Example 2
Input: window_fold([2, 4, 8, 16], 2, 'multiply')
Output: [8, 32, 128]
Example 3
Input: window_fold([7, 3, 15, 11], 3, 'bitwise_and')
Output: [3, 3]
Hints
Hint 1
Recomputing each block from scratch costs O(n*k). Think about what information from the previous block can be reused when the block moves one step right.
Hint 2
Subtracting the outgoing element works for addition, but fails for AND (no inverse) and for multiplication when zeros are present. Look for an approach that needs only associativity.
Hint 3
Model the window as a queue built from two stacks. Each stack entry stores a running fold: the back stack folds left-to-right as items are pushed, and when the front stack is empty, move everything over, recomputing folds so the oldest element is on top. The answer is the front fold combined (front on the left) with the back fold.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Recomputing every window costs O(n·k), which is too slow at the limits. Tricks based on undoing an operation do not generalize: subtraction works for addition, but AND has no inverse and division breaks when a window contains zero. The approach that needs only associativity is a queue built from two stacks, where every stack entry also stores a running fold.
- Back stack. New elements are pushed here. Each entry stores
(value, fold), wherefold = combine(previous_fold, value), i.e. the left-to-right fold of the back stack from its bottom to that entry. - Front stack. Elements leave the window from here. Each entry stores
(value, fold), wherefold = combine(value, fold_below), i.e. the fold from that entry down through the rest of the front stack. Since the oldest element is on top, its fold covers the whole front part in order. - Sliding. To remove the oldest element, if the front stack is empty, pop everything from the back stack and push it onto the front stack (this reverses order and recomputes folds). Then pop the front stack.
- Reading the window. The window is the front part followed by the back part, so the answer is
combine(front_top_fold, back_top_fold). If one stack is empty, use the other's top fold.
Why it is correct
The window is always a prefix (in the front stack) followed by a suffix (in the back stack). The back top fold equals the ordered fold of the suffix, and the front top fold equals the ordered fold of the prefix. Popping the front leaves the next entry, whose stored fold already covers exactly the remaining prefix. By associativity, prefix ⊕ suffix equals the full left-to-right fold of the window. The prefix is always the left operand, so commutativity is never needed. No inverse is used, so zeros and AND are handled correctly.
Complexity
- Time: O(n) combine calls amortized. Each element is pushed to the back stack once, moved to the front stack at most once, and popped once.
- Space: O(k) beyond the output.
With "multiply", Python integers can grow to roughly 20 bits per element, so each combine is big-integer arithmetic rather than truly constant time.
Reference solution
from typing import List
def window_fold(values: List[int], k: int, operation: str) -> List[int]:
def combine(a: int, b: int) -> int:
if operation == "add":
return a + b
if operation == "multiply":
return a * b
if operation == "bitwise_and":
return a & b
raise ValueError("operation must be 'add', 'multiply', or 'bitwise_and'")
n = len(values)
result = []
back = [] # (value, fold of back stack from bottom to this entry)
front = [] # (value, fold from this entry down to front stack bottom)
def push_back(value: int) -> None:
agg = value if not back else combine(back[-1][1], value)
back.append((value, agg))
def transfer() -> None:
while back:
value, _ = back.pop()
agg = value if not front else combine(value, front[-1][1])
front.append((value, agg))
def pop_front() -> None:
if not front:
transfer()
front.pop()
def current() -> int:
if not front:
return back[-1][1]
if not back:
return front[-1][1]
return combine(front[-1][1], back[-1][1])
for v in values[:k]:
push_back(v)
result.append(current())
for right in range(k, n):
pop_front()
push_back(values[right])
result.append(current())
return result