Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find range sum of sorted subarray sums using Python
Suppose we have an array nums with n positive elements. We need to compute the sum of all non-empty contiguous subarrays of nums, sort them in non-decreasing order, and then find the sum of elements from index left to index right (1-indexed) in the sorted array. The answer should be returned modulo 10^9 + 7.
Problem Understanding
For example, if nums = [1,5,2,6], left = 1, and right = 5:
- All subarray sums are: 1, 5, 2, 6, 6, 7, 8, 8, 13, 14
- After sorting: [1, 2, 5, 6, 6, 7, 8, 8, 13, 14]
- Sum from index 1 to 5: 1 + 2 + 5 + 6 + 6 = 20
Algorithm Steps
To solve this problem, we follow these steps ?
-
m:= 10^9 + 7 (modulo value) -
n:= size of nums -
subarray_sums:= a new list to store all subarray sums - For each starting position
ifrom 0 to n-1: - For each ending position
jfrom i to n-1: - If
i == j, appendnums[j]to subarray_sums - Otherwise, append the sum of current element plus previous subarray sum
- Sort the subarray_sums list
- Calculate sum from index
left-1toright-1and return modulo m
Implementation
def solve(nums, left, right):
m = 10**9 + 7
n = len(nums)
subarray_sums = []
# Generate all subarray sums
for i in range(n):
for j in range(i, n):
if i == j:
subarray_sums.append(nums[j])
else:
# Add current element to the previous subarray sum
subarray_sums.append((nums[j] + subarray_sums[-1]) % m)
# Sort the subarray sums
subarray_sums.sort()
# Calculate sum from left to right (1-indexed)
result = sum(subarray_sums[left-1:right])
return result % m
# Test the function
nums = [1, 5, 2, 6]
left = 1
right = 5
print(solve(nums, left, right))
The output of the above code is ?
20
How It Works
The algorithm generates all possible contiguous subarrays by using nested loops. For each starting position i, it extends the subarray to position j and calculates the sum efficiently by adding the current element to the previous subarray sum. This avoids recalculating the entire sum for each subarray.
Time and Space Complexity
- Time Complexity: O(n²) for generating subarray sums + O(n² log n) for sorting = O(n² log n)
- Space Complexity: O(n²) to store all subarray sums
Conclusion
This solution efficiently generates all subarray sums, sorts them, and calculates the range sum. The modulo operation prevents integer overflow for large sums while maintaining correctness.
