You are given an array of integers nums. Write a function to find the number of subarrays that have a sum that is a power of two. Please write a function that solves this problem, and explain your algorithm.
Assistant
We need to count subarrays whose sum is a power of two. Given array of integers (could be negative? The problem statement says "array of integers", so possibly negative. But powers of two are positive (2^0=1,2^1=2,...). Usually sum of subarray could be negative? If negative, it can't equal a positive power of two. So only consider subarrays with positive sum that equals a power of two. But also sum zero? 0 is not a power of two (unless you consider 2^{-inf}? no). So only positive powers.
We need efficient solution. Constraints not given. Typically we want O(n log n) or O(n * something). Could be up to 10^5 length? We need to think.
Approach: Use prefix sums. Let prefix[i] = sum of nums[0..i-1] (prefix[0]=0). Then subarray sum from i to j-1 = prefix[j] - prefix[i]. We want prefix[j] - prefix[i] = 2^k for some k>=0. So for each j, we need count of i < j such that prefix[i] = prefix[j] - 2^k.
So we can iterate j from 1..n, and for each j, we consider all powers of two up to some max. The sum of subarray could be as large as the total sum of array (if all positive). But if there are negative numbers, prefix can be arbitrary large positive or negative, but the difference must be a power of two. The maximum absolute sum might be bounded by sum of absolute values? Let's think: If numbers can be large (like up to 10^9), and array length up to 10^5, total sum could be up to 10^14. Powers of two up to that: about log2(10^14) ≈ 47. So number of powers is small (maybe up to 60). So we can for each j, loop over all powers of two (k from 0 to, say, 60) and check if prefix[j] - 2^k exists among previous prefixes. Use a hashmap (dictionary) to store counts of prefix sums seen so far. That gives O(n * num_powers) time. That's O(n * 60) = O(n). Good.
But careful: if numbers can be negative, prefix sums can be negative and we may have many distinct prefix sums. That's okay.
Edge: 2^k might be larger than possible difference? But we can compute powers up to some max that is safe. Since prefix sums are integers, we can compute max absolute prefix sum? Actually we don't need to bound; we can precompute powers up to some large limit based on constraints. But if numbers are up to 10^9 and n up to 10^5, max absolute prefix sum could be 10^14. So we can precompute powers of two up to, say, 2^60 ≈ 1e18, which is safe for 64-bit integers. Or we can compute dynamically: while power <= (max_prefix - min_prefix) maybe? But easier: just compute all powers of two from 1 to 2^60 (or up to 2^62) because Python ints are unbounded.
But we also need to consider that subarray sum could be zero? No, zero is not a power of two.
So algorithm:
Compute prefix sum array of length n+1, with prefix[0]=0.
Initialize a dictionary count that maps prefix sum values to number of times they have occurred. Start with count[0] = 1 (prefix 0 seen once).
Initialize result = 0.
For j from 1 to n:
current_prefix = prefix[j]
For each power p in powers_of_two (list precomputed):
target = current_prefix - p
if target in count: result += count[target]
Then update count[current_prefix] += 1 (or set to 1 if not exists)
Return result.
Complexities: O(n * num_powers). With num_powers ~ 60, O(n). Memory: O(n) for prefix counts.
But we need to ensure that powers_of_two includes all possible powers that could be sum of any subarray. The sum of a subarray can be negative? Only if numbers negative, but power of two is positive, so sum must be positive. So we only need positive powers. So p >= 1.
But what if the array contains negative numbers and the subarray sum could be positive but less than some large power? That's fine. The loop over all powers up to some max where p <= max_possible_sum? Actually if p is larger than current_prefix - min_prefix, then target = current_prefix - p will be less than any possible prefix seen? But we can still check; if it's not in the dict, it's fine. So we can just loop over a fixed set of powers that covers all possible sums given constraints. We need to choose max power based on possible max absolute sum. But if we choose too small, we might miss some sums that are powers of two beyond that limit. But we can compute the maximum absolute sum as the max difference between any two prefix sums. That could be as high as sum of absolute values? Actually consider prefix sums: They can be positive or negative. The difference between two prefix sums is the subarray sum. The maximum absolute subarray sum could be the sum of absolute values of all numbers if they are all same sign? Actually if all positive, the maximum subarray sum is total sum. If all negative, the maximum subarray sum (positive?) Actually subarray sum could be negative if we take any subarray? But we only care about positive sums that equal a power of two. So the maximum positive subarray sum is at most the sum of positive contributions minus negative? Actually the maximum subarray sum could be the total sum if all positive, or it could be a large positive if you have a mix? But the maximum possible absolute subarray sum is bounded by the sum of absolute values of all numbers, because worst case you take entire array and sum is sum(nums). But there could be a subarray that is larger than total sum if there are negatives? No, adding negatives reduces sum. So the maximum subarray sum (positive) is at most the sum of all positive numbers, which is <= sum of absolute values. So we can bound maximum possible sum by total_abs_sum = sum(abs(x) for x in nums). But careful: if there are negative numbers, the sum of a subarray could be positive even if total sum is negative? For example, nums = [5, -2, 10] total sum=13, subarray [10] sum=10. That's less than total sum. In general, maximum subarray sum (Kadane's) is at most total sum of positive numbers, which is <= total_abs_sum. So max subarray sum <= total_abs_sum. So we can precompute powers up to total_abs_sum (maybe plus some). But total_abs_sum might be up to 10^14 if n=10^5 and each abs up to 10^9 -> 10^14. That's about 2^47. So we need powers up to maybe 2^47 or a bit more. That's still < 60. So fixed set up to 2^60 is safe.
But if numbers can be huge (like up to 10^18), we may need more powers. But Python ints are fine. But we need to be careful about performance: iterating 60 times per element is okay for n=10^5 (6 million ops). For n=10^6, 60 million ops, still okay in Python? Might be borderline but okay. Could optimize by precomputing set of powers and iterating. That's fine.
Edge Cases:
Empty subarray? Not considered (subarray length >=1). Our prefix approach with i<j ensures non-empty? Actually subarray from i to j-1, with i<j. Since we require i<j and we have count of prefix sums seen before j. We start with count[0]=1 (i=0). That gives subarray starting at index 0 if prefix[j] itself equals a power of two, because target = prefix[j] - p = 0 => p = prefix[j]. That's valid if prefix[j] itself is a power of two. That corresponds to subarray from 0 to j-1. So it's correct.
Potential pitfalls: The number of powers to consider might be huge if the total_abs_sum is extremely large (like 10^18 -> powers up to 2^60). That's still 60. If total_abs_sum is 10^30 (if numbers can be huge, like 10^15 and n=10^5, sum=10^20) then powers up to 2^66? That's still ~66. So number of powers grows as log2(max_sum). That's at most around 70 for 10^21. So still O(1) per j.
Thus algorithm is efficient.
We should also consider negative sums? We only check positive p. But if prefix[j] - p is negative and that negative value appears as a prefix sum? That's okay: target can be negative. That's fine because prefix sums can be negative. So we don't restrict sign.
Thus solution works.
We need to write a function, maybe named countPowerOfTwoSubarrays(nums). It returns integer.
For j=1: prefix=1. Check p=1 => target=0 exists count(0)=1 => result=1 (subarray [1] sum=1). p=2 => target=-1 not exist. p=4 => -3 no. etc.
Update count: {0:1,1:1}
j=2: prefix=3. p=1 => target=2 not exist. p=2=> target=1 exists count(1)=1 => result=2 (subarray [2] sum=2? Actually sum of subarray from index? Let's see: prefix[2]-prefix[1]=3-1=2 => subarray [2] yes). p=4=>-1 no. p=8=>-5 no. Also p=? 3 itself? Not a power. So now result=2.
Update count: {0:1,1:1,3:1}
j=3: prefix=6. p=1=>5 no. p=2=>4 no. p=4=>2 no. p=8=>-2 no. So none.
j=4: prefix=10. p=1=>9 no. p=2=>8 no. p=4=>6 => target=6 exists count(6)? Not yet (we haven't added prefix[3]? Actually prefix[3]=6 is already in count from j=3? After j=3 we added prefix[3]=6. So at j=4, count includes 0,1,3,6. So target=6 exists count(6)=1 => result=3 (subarray from index 3 to 3? Actually prefix[4]-prefix[3]=10-6=4 => subarray [4] sum=4). Also p=8=>2 no. p=16=>-6 no. So result=3. Also maybe subarray [1,2,3] sum=6? Not a power. So total 3: [1],[2],[4]. Also maybe [1,2,3,4]? sum=10 not power. So correct.
If we include negative numbers: nums = [2,-1,2]. prefix = [0,2,1,3]. Powers:1,2,4,...
j=1: prefix=2. p=1=>1 not exist. p=2=>0 exists => result=1 (subarray [2] sum=2). p=4=>-2 no.
count: {0:1,2:1}
j=2: prefix=1. p=1=>0 exists => result=2 (subarray [2,-1] sum=1). p=2=>-1 no. p=4=>-3 no.
count: {0:1,2:1,1:1}
j=3: prefix=3. p=1=>2 exists count(2)=1 => result=3 (subarray [-1,2] sum=1? Actually prefix[3]-prefix[2]=3-1=2? Wait compute: For p=1 target=2? Actually p=1 => target = 3-1=2 => count(2)=1 gives subarray sum=1? Check: subarray from i=1 (prefix=2) to j-1=2? prefix[3]=3, prefix[1]=2 => sum=1. That's subarray [-1]? Actually nums[1]= -1? Indices: nums[0]=2, nums[1]= -1, nums[2]=2. Subarray from i=1 to 2? i is prefix index: i=1 means start at index 1? prefix[i] is sum up to index i-1. So subarray from index i to j-1. If i=1, j=3 => subarray indices 1,2: [-1,2] sum=1. That's correct. p=2 => target=1 exists count(1)=1 => result=4 (subarray [2] sum=2? Actually prefix[3]-prefix[2]=3-1=2 => subarray [2] at index 2). p=4=> -1 no. So total 4: [2] (first), [2,-1] sum=1, [-1,2] sum=1, [2] (last). Check [2] first and last both sum=2. So correct.
Also subarray [2,-1,2] sum=3 not power. So works.
Thus algorithm is sound.
Potential improvements: If n is huge (like 10^6) and we do 60 checks per element, it's fine. Could we do less by limiting powers based on possible range? Could compute min_prefix and max_prefix and bound p between 1 and max_prefix - min_prefix, but that requires scanning first to compute min/max. Could also precompute powers up to total_abs_sum. But fixed 60 is fine.
But careful: prefix[j] - p could be a large negative number that hasn't been seen; dictionary lookup is O(1) average.
So implementation straightforward.
Now write the function with explanation.
Also consider possibility of overflow? Python fine.
Edge: empty array? n=0 => result=0.
We'll implement.
But the problem statement: "You are given an array of integers nums. Write a function to find the number of subarrays that have a sum that is a power of two." So they want count.
We'll provide a solution with O(n log M) where M is max sum.
Now produce final answer.
We'll include detailed explanation and complexity analysis.
Implementation:
python
This is O(n * len(powers)). Good.
But we should consider if total_abs is zero, we skip loop over powers? Yes, powers empty means ans stays 0. But there might still be subarray sum that is power of two? No, because any subarray sum is zero (since all numbers zero), so none. So correct.
But what about when total_abs is zero but we have some negative numbers? Actually total_abs sum of absolute values can't be zero unless all numbers are zero. So fine.
Potential performance: Using .get inside loop; we could also store prefix_count as a normal dict.
Complexity: O(n * log(total_abs)). Space: O(n) for dict.
Now we need to write explanation.
We also need to consider that the array could be large (like 10^5) and numbers could be large (like 10^9). Our algorithm works.
Now produce final answer with function and explanation.
But we might need to consider integer overflow? Not in Python.
Now we should write the code in a clean way and maybe include some comments.
Now produce final answer.
Solution Explanation
For a subarray nums[l..r] (inclusive) its sum is
code
sum(l, r) = prefix[r+1] - prefix[l]
where prefix[i] is the sum of the first i elements (prefix[0]=0).
We want this sum to be a power of two, i.e. prefix[r+1] - prefix[l] = 2^k for some k ≥ 0.
So for every right end j (which corresponds to prefix[j]) we need to count how many earlier
prefixes prefix[i] (i < j) satisfy
code
prefix[i] = prefix[j] - 2^k .
If we know how many times each prefix value has appeared before j, we can answer the query
for j in O(#powers) time.
Algorithm
Pre‑compute all relevant powers of two
Any subarray sum cannot exceed the sum of absolute values of the whole array (total_abs),
because a positive subarray sum is at most the sum of absolute values inside that subarray.
Therefore we generate all 2^k such that 2^k ≤ total_abs.
Their count is ⌊log₂(total_abs)⌋ + 1 (at most about 60 for typical constraints).
Traverse the array while maintaining a hash map cnt cnt[p] = how many times prefix sum p has been seen so far.
Initialise cnt[0] = 1 (empty prefix).
For each elementx in nums
update the running prefix sum: cur += x.
for every power p in the pre‑computed list, add cnt.get(cur - p, 0) to the answer.
finally increment cnt[cur].
Return the accumulated answer.
Correctness Proof
We prove that the algorithm returns exactly the number of subarrays whose sum is a power of two.
Lemma 1
For any subarray nums[l..r] its sum equals 2^k for some k ≥ 0iffprefix[r+1] - prefix[l] = 2^k.
Proof. By definition of prefix sums, prefix[r+1] is the sum of the first r+1 elements,
prefix[l] the sum of the first l elements. Their difference is exactly the sum of the
contiguous segment from index l to r. ∎
Lemma 2
During the iteration, just before processing the element at index j (i.e. computing the
prefix prefix[j]), the map cnt contains exactly the counts of all prefix values
prefix[i] with i < j.
Proof. Initially cnt has only prefix[0]=0. After processing each element we add the
current prefix to cnt. Hence after finishing index j‑1, all prefixes up to j are stored.
Before the next update (for index j) the map therefore holds exactly the prefixes with
indices < j. ∎
Lemma 3
For a fixed right end j, the quantity
code
add = Σ_{p ∈ Powers} cnt.get(prefix[j] - p, 0)
equals the number of subarrays ending at position j‑1 whose sum is a power of two.
Proof. Consider any power p. A subarray ending at j‑1 with sum p must start at some
i < j and satisfy prefix[j] - prefix[i] = p (by Lemma 1), i.e. prefix[i] = prefix[j] - p.
All such i correspond exactly to the occurrences of the value prefix[j] - p among earlier
prefixes. By Lemma 2 the map cnt stores how many times this value appears. Summing over
all powers counts every qualifying start index once, because each subarray sum equals exactly
one power of two. ∎
Lemma 4
After processing the whole array, the accumulated answer ans equals the total number of
subarrays whose sum is a power of two.
Proof. The algorithm processes each position j (from 1 to n) and adds the quantity
from Lemma 3 to ans. This quantity counts all subarrays that end at j‑1 and satisfy
the condition, and no subarray is counted at any other step. Since every subarray has a
unique right end, the sum over all j counts each valid subarray exactly once. ∎
Theorem
countPowerOfTwoSubarrays(nums) returns the number of contiguous subarrays of nums whose
sum is a power of two.
Proof. By Lemma 4 the algorithm’s final ans equals the total number of qualifying
subarrays. The function returns ans, therefore it is correct. ∎
Complexity Analysis
Letn = len(nums) and P = ⌊log₂(total_abs)⌋ + 1 (number of powers, at most 60).
Time: O(n · P) – we iterate once over the array and for each element scan all powers.
Since P is bounded by a constant (≤ 60 for total_abs up to 10^18), the algorithm is
effectively linear O(n).
Space: O(n) for the hash map storing prefix counts (at most n+1 distinct keys).
Reference Implementation (Python 3)
python
from collections import defaultdict
from typing import List
def countPowerOfTwoSubarrays(nums: List[int]) -> int:
"""
Returns the number of contiguous subarrays of `nums` whose sum is a power of two.
"""
# 1. Determine an upper bound for any possible subarray sum.
total_abs = sum(abs(x) for x in nums)
# 2. Pre‑compute all powers of two that could appear (1, 2, 4, ... ≤ total_abs).
powers = []
p = 1
while p <= total_abs:
powers.append(p)
p <<= 1 # multiply by 2
# 3. Scan the array, maintain prefix counts.
prefix_count = defaultdict(int)
prefix_count[0] = 1 # empty prefix
cur = 0
ans = 0
for x in nums:
cur += x
# For each power, count earlier prefixes that would give a subarray sum = power.
for power in powers:
ans += prefix_count.get(cur - power, 0)
# Record the current prefix for future positions.
prefix_count[cur] += 1
return ans
Explanation of the code follows exactly the algorithm proven correct above.
def countPowerOfTwoSubarrays(nums):
n = len(nums)
# Precompute powers of two up to a limit
# Determine a safe upper bound: maximum possible absolute subarray sum
# We can compute total absolute sum or just use a large constant like 2**60.
# Since Python ints are arbitrary, we can compute powers until they exceed some huge bound.
# But to be safe, we can compute all powers of two up to (max_possible_sum), where max_possible_sum is sum of absolute values of nums.
total_abs = sum(abs(x) for x in nums)
powers = []
p = 1
while p <= total_abs * 2: # maybe multiply by 2 to be safe?
powers.append(p)
p <<= 1
# But if total_abs is 0, then we still need at least power=1? But if total_abs=0, all numbers are 0 => subarray sum 0 not power, so result 0. But powers list may be empty; but we could still just have [1]? Actually if total_abs=0, then p=1 >0, so loop not entered, powers empty. Then we would not check any power, resulting 0, correct. But we need to be careful: if there is a subarray sum that is a power of two but total_abs=0? No, because all numbers zero, sum zero. So safe.
# But we might also consider the case where total_abs is small but there is a prefix difference that equals a power of two that is larger than total_abs? Could that happen? Suppose prefix[j] - prefix[i] = power > total_abs. But prefix[j] and prefix[i] are each between min_prefix and max_prefix. The difference max-min is at most total_abs? Actually max_prefix - min_prefix <= total_abs? Let's examine: prefix sums are cumulative. The maximum difference between any two prefix sums is at most sum of absolute values? Not exactly: For example, nums = [10, -5, 10]. total_abs=25. prefix: 0,10,5,15. max-min = 15-0=15 which is less than total_abs. Could we have a difference larger than total_abs? Consider an array with alternating signs that cause prefix to go very high then very low? The difference between a later high and an earlier low could be larger than total_abs? total_abs is sum of absolute values, which is the total variation but not exactly. Actually the maximum possible difference between any two prefix sums is bounded by the sum of absolute values of the elements in the subarray that gives that difference. If we take subarray from i to j-1, sum = prefix[j] - prefix[i]. The absolute value of that sum is at most sum_{k=i}^{j-1} |nums[k]| <= total_abs. So any subarray sum's absolute value <= total_abs. So yes, if a power of two equals the sum, then that power <= total_abs. So we can safely bound powers up to total_abs. But careful: total_abs is sum of absolute values of all elements. That is an upper bound on any subarray sum's absolute value. Because any subarray is a subset of contiguous elements; sum of absolute values of that subarray <= total_abs. So the sum itself (if positive) <= total_abs. So we can set max_power = total_abs (if total_abs >=1). But total_abs might be zero, then no positive sum. So loop: p=1; while p <= total_abs: add. That's correct. But if total_abs is very large, we may generate many powers? Number of powers ~ log2(total_abs) ~ up to 60 for total_abs up to 1e18. That's fine. So we can compute powers based on total_abs. That ensures we don't miss any. But note: total_abs could be zero if all zeros; then powers empty. That's fine.
Alternatively, we could compute powers up to 2**60 regardless. But using total_abs is more precise and maybe smaller if total_abs small.
But caution: total_abs might be negative? sum of abs is non-negative. Good.
So implement: compute total_abs = sum(abs(x) for x in nums). Then generate powers up to total_abs.
But wait: what if total_abs is less than some power that could appear as a sum because the sum might be larger than total_abs? Is that possible? Consider array [100, -50, 100]. total_abs = 250. Subarray sum [100] =100, [100,-50,100]=150, [100] at end =100. All <= total_abs. Could we get a sum that is larger than total_abs? Suppose array has positive and negative numbers, but the sum of absolute values of the subarray could be larger than the total_abs? No, because total_abs is sum of absolute values of all elements. Any subarray's sum of absolute values is at most total_abs. And the actual sum (with signs) is less than or equal to the sum of absolute values in absolute value, but the positive sum cannot exceed the sum of absolute values of the subarray. Because if all numbers in the subarray are positive, the sum equals the sum of absolute values. If some are negative, the sum is less. So the maximum possible subarray sum (positive) is at most the maximum sum of absolute values of any contiguous subarray. But that maximum could be less than total_abs if negatives break positivity. But total_abs is an upper bound for any subarray's absolute sum. So if we only generate powers up to total_abs, we cover any possible positive subarray sum because any positive subarray sum <= sum of absolute values of that subarray <= total_abs. So yes, it's safe.
But is there a scenario where the sum of absolute values of a subarray exceeds total_abs? No, because total_abs is sum of absolute values of all elements, and any subarray is a subset of those elements, so its sum of absolute values is <= total_abs. So the positive sum (if it's positive) is <= that sum of absolute values. So yes.
Thus powers up to total_abs is sufficient.
But what about the case where total_abs is 0? Then no positive sums, powers empty, result 0. Good.
But careful: The subarray sum could be exactly 0? Not a power of two, so ignore.
So algorithm: generate powers = [1<<k for k in range(0, total_abs.bit_length())] maybe? Since total_abs may be large, we want powers up to total_abs inclusive. For example, total_abs = 5, powers: 1,2,4. 8 >5 so stop. That's fine. But what if there is a subarray sum that is a power of two equal to 1? That's included. So we generate while p <= total_abs: powers.append(p); p <<= 1.
Edge: total_abs could be huge, but bit_length is manageable.
Implementation details: We'll use a dictionary `prefix_count` with default 0. We'll iterate through prefix sums, but we can compute on the fly without storing full prefix array to save memory. We can just maintain a running prefix sum and update dictionary.
Pseudo:
```python
def countPowerOfTwoSubarrays(nums):
total_abs = sum(abs(x) for x in nums)
powers = []
p = 1
while p <= total_abs:
powers.append(p)
p <<= 1
# if total_abs is 0, powers empty.
prefix_count = defaultdict(int)
prefix_count[0] = 1
cur_sum = 0
ans = 0
for x in nums:
cur_sum += x
for power in powers:
ans += prefix_count.get(cur_sum - power, 0)
prefix_count[cur_sum] += 1
return ans