Program to find sum of the sum of all contiguous sublists in Python

Given a list of numbers, we need to find the sum of all possible contiguous subarrays and return the result modulo 109 + 7. This problem can be solved efficiently by calculating how many times each element appears in all subarrays.

For the input nums = [3, 4, 6], we have these contiguous subarrays: [3], [4], [6], [3, 4], [4, 6], [3, 4, 6]. Their sums are 3, 4, 6, 7, 10, 13 respectively, totaling 43.

Understanding the Pattern

Instead of generating all subarrays, we can calculate how many times each element contributes to the final sum. For an element at index i in an array of size N:

  • It appears in (i + 1) * (N - i) subarrays
  • (i + 1) represents possible starting positions
  • (N - i) represents possible ending positions

Algorithm Steps

  • Initialize N as the size of the input array
  • Initialize ans to 0
  • For each element at index i, calculate its contribution: (i + 1) * (N - i) * nums[i]
  • Add this contribution to ans
  • Return ans modulo 109 + 7

Implementation

class Solution:
    def solve(self, nums):
        N = len(nums)
        ans = 0
        for i in range(len(nums)):
            n = nums[i]
            ans += (i + 1) * (N - i) * n
        return ans % 1000000007

# Test the solution
ob = Solution()
result = ob.solve([3, 4, 6])
print(f"Sum of all contiguous subarray sums: {result}")
Sum of all contiguous subarray sums: 43

How It Works

For nums = [3, 4, 6]:

  • Element 3 (index 0): appears in (0+1) * (3-0) = 3 subarrays, contributes 3 * 3 = 9
  • Element 4 (index 1): appears in (1+1) * (3-1) = 4 subarrays, contributes 4 * 4 = 16
  • Element 6 (index 2): appears in (2+1) * (3-2) = 3 subarrays, contributes 6 * 3 = 18
  • Total: 9 + 16 + 18 = 43

Alternative Implementation

def sum_of_subarray_sums(nums):
    """
    Calculate sum of all contiguous subarray sums
    """
    MOD = 10**9 + 7
    n = len(nums)
    total_sum = 0
    
    for i in range(n):
        # Each element nums[i] appears in (i+1)*(n-i) subarrays
        contribution = nums[i] * (i + 1) * (n - i)
        total_sum = (total_sum + contribution) % MOD
    
    return total_sum

# Test with example
nums = [3, 4, 6]
result = sum_of_subarray_sums(nums)
print(f"Input: {nums}")
print(f"Sum of all subarray sums: {result}")
Input: [3, 4, 6]
Sum of all subarray sums: 43

Time and Space Complexity

  • Time Complexity: O(n) where n is the length of the input array
  • Space Complexity: O(1) as we only use constant extra space

Conclusion

This efficient approach calculates the contribution of each element to all subarrays in O(n) time. By understanding how many times each element appears across all contiguous subarrays, we avoid the O(n³) brute force solution of generating all subarrays explicitly.

Updated on: 2026-03-25T10:43:51+05:30

502 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements