KatInterview

Fixed-Width Window Folds with Add, Multiply, or AND

Stacks & QueuesAuto-graded · 21 test cases
MediumAuto-gradedStacks & Queuessliding-windowtwo-stacksassociative-operation

Last 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 values is an integer in [-10^6, 10^6]
  • operation is 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.