Window Sums Within [k, 2k] for Power-of-Two Lengths
Arrays & HashingAuto-graded · 22 test casesLast 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:
- Its length is a power of two (1, 2, 4, 8, ...).
- The sum of its elements is at least
kand at most2 * 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 byendwhen two pairs share the samestart. - If nothing qualifies (including when
valuesis 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 npairs).
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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A block is fully determined by its start index and its length. Because the length must be a power of two, an array of size n allows only about log2(n) + 1 lengths: 1, 2, 4, and so on up to the largest power of two not exceeding n. That means there are at most n * (log2(n) + 1) candidate blocks, far fewer than the O(n^2) blocks in general.
To test each candidate in constant time, build a prefix-sum array where prefix[i] is the sum of the first i elements. The sum of the block covering indices start through stop - 1 is prefix[stop] - prefix[start]. If that value lies in [k, 2k], record [start, stop - 1].
Iterating start from small to large in the outer loop and lengths from small to large in the inner loop produces the pairs already sorted by (start, end), so no extra sorting is needed. Once start + length exceeds n, all longer lengths also overflow, so the inner loop can break.
Why it is correct
Every qualifying block corresponds to exactly one pair (start, power-of-two length) that fits in the array, and the loops visit each such pair once. The prefix difference equals the true block sum for any integers, positive or negative, so the range test is exact. A fixed-length window never relies on monotonic sums, which is why negative values need no special treatment. If k < 0, the interval is empty and the literal comparison rejects everything.
Complexity
- Time:
O(n)for the prefix sums plusO(n log n)candidate checks, soO(n log n)overall. This is also optimal in the worst case, since the output itself can holdTheta(n log n)pairs (for example, all zeros withk = 0). - Space:
O(n)for the prefix array, plus the output.
Reference solution
from typing import List
def power_of_two_blocks_in_range(values: List[int], k: int) -> List[List[int]]:
n = len(values)
prefix = [0] * (n + 1)
for i, v in enumerate(values):
prefix[i + 1] = prefix[i] + v
lengths = []
length = 1
while length <= n:
lengths.append(length)
length <<= 1
result = []
for start in range(n):
for length in lengths:
stop = start + length
if stop > n:
break
total = prefix[stop] - prefix[start]
if k <= total <= 2 * k:
result.append([start, stop - 1])
return result