Program to find sum of the 2 power sum of all subarray sums of a given array in Python

Given an array, we need to find all possible non-empty subarrays, calculate the sum of each subarray, then compute the sum of 2 raised to the power of each subarray sum. The result should be returned modulo (109 + 7).

For an array with n elements, there are (2n - 1) non-empty subarrays. For each subarray sum Si, we calculate 2Si and sum all these values to get P = 2S1 + 2S2 + 2S3 + ... + 2S(2n-1).

Example Walkthrough

For the array A = [2, 2, 3], the non-empty subarrays and their sums are ?

  • [2] ? sum = 2, so 22 = 4
  • [2] (second element) ? sum = 2, so 22 = 4
  • [3] ? sum = 3, so 23 = 8
  • [2, 2] ? sum = 4, so 24 = 16
  • [2, 3] (first 2 and 3) ? sum = 5, so 25 = 32
  • [2, 3] (second 2 and 3) ? sum = 5, so 25 = 32
  • [2, 2, 3] ? sum = 7, so 27 = 128

Total sum: 4 + 4 + 8 + 16 + 32 + 32 + 128 = 224

Algorithm

The key insight is that each element contributes to multiple subarrays. We can use the mathematical property that for each element at position i, it appears in exactly (i + 1) × (n - i) subarrays. Using this pattern, we can derive the formula ?

  • Initialize ans = 1 and modulo m = 109 + 7
  • For each element el in the array:
    • Multiply ans by (1 + 2el mod m)
    • Take modulo to prevent overflow
  • Return (ans - 1) mod m

Implementation

def solve(A):
    ans = 1
    m = 10**9 + 7
    
    for el in A:
        ans *= (1 + pow(2, el, m))
        ans %= m
    
    return (m + ans - 1) % m

# Test with example
A = [2, 2, 3]
result = solve(A)
print(f"Array: {A}")
print(f"Sum of 2^(subarray_sums): {result}")
Array: [2, 2, 3]
Sum of 2^(subarray_sums): 224

How It Works

The algorithm uses the mathematical property that the contribution of each element can be calculated independently. The expression (1 + 2el) for each element accounts for all possible ways that element can contribute to different subarray sums.

Using pow(2, el, m) efficiently computes 2el mod m using fast exponentiation, which is crucial for large values to prevent integer overflow.

Conclusion

This solution efficiently computes the sum of 2 raised to all subarray sums using mathematical optimization. The time complexity is O(n log max(A)) where n is the array length, making it suitable for large inputs.

Updated on: 2026-03-26T18:24:24+05:30

360 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements