KatInterview

Window Sums Within [k, 2k] for Power-of-Two Lengths

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingprefix-sumsliding-windowsubarray

Last updated

Enumerate every subarray whose length is a power of two and whose sum falls in [k, 2k], using prefix sums to get an O(n log n) solution with ordered output.

You are given a list of integers values and an integer k.

A contiguous block of values is called qualifying if both of these hold:

  1. Its length is a power of two (1, 2, 4, 8, ...).
  2. The sum of its elements is at least k and at most 2 * k, with both ends included.

Return every qualifying block as a pair [start, end], where start and end are zero-based, inclusive indices of the first and last element of the block.

Output format

  • The result is a list of [start, end] pairs.
  • Sort the pairs in ascending order by start, and by end when two pairs share the same start.
  • If nothing qualifies (including when values is empty), return an empty list.

The elements of values may be negative, zero, or positive, and k may be negative or zero as well. Apply the rule k <= sum <= 2 * k literally in every case. For example, if k is negative then 2 * k < k, so no sum can satisfy it.

Aim for a solution that does clearly better than checking all O(n^2) subarrays.

Constraints

  • 0 <= len(values) <= 10^5
  • -10^4 <= values[i] <= 10^4
  • -10^9 <= k <= 10^9
  • Each block is identified by its position, so the same numbers appearing at different positions count as different blocks.
  • The output may be large (up to roughly n log n pairs).

Examples

Example 1

Input: power_of_two_blocks_in_range([1, 2, 3, 4], 3)

Output: [[0, 1], [1, 2], [2, 2], [3, 3]]

Example 2

Input: power_of_two_blocks_in_range([5, 1, 2, 8, 1], 6)

Output: [[0, 1], [1, 4], [2, 3], [3, 3], [3, 4]]

Example 3

Input: power_of_two_blocks_in_range([2, -1, 4, -2, 3], 3)

Output: [[0, 3], [1, 2], [1, 4], [2, 2], [4, 4]]

Example 4

Input: power_of_two_blocks_in_range([0, 0, 0, 0], 0)

Output: [[0, 0], [0, 1], [0, 3], [1, 1], [1, 2], [2, 2], [2, 3], [3, 3]]

Hints

Hint 1

Only about log2(n) + 1 lengths are allowed (1, 2, 4, ...). Count how many (start, length) pairs that gives in total.

Hint 2

Build a prefix-sum array so the sum of any block can be read in constant time as prefix[end + 1] - prefix[start].

Hint 3

Loop over start in the outer loop and over increasing power-of-two lengths in the inner loop. The pairs then come out already sorted, and you can stop the inner loop as soon as a block no longer fits. Negative numbers need no special handling.