Range Sum of Sorted Subarray Sums

Generate all subarray sums, sort, and sum the requested index range modulo 1e9+7.

Medium
Time O(n^2 log n) Space O(n^2)
LeetCode
4 min read
sorting prefix-sum

Problem#

Given an array nums of length n, enumerate the sums of all n*(n+1)/2 non-empty contiguous subarrays. Sort them, and return the sum of values from index left to right inclusive (1-indexed), modulo 10^9 + 7.

Examples#

  • nums = [1,2,3,4], n = 4, left = 1, right = 513
  • nums = [1,2,3,4], n = 4, left = 3, right = 46
  • nums = [1,2,3,4], n = 4, left = 1, right = 1050

Constraints#

  • 1 <= nums.length <= 1000, 1 <= nums[i] <= 100, 1 <= left <= right <= n * (n + 1) / 2.

Approach#

There are at most ~500500 subarray sums. Compute them in O(n^2) with running totals, sort once, then sum the range.

Solution#

Range Sum of Sorted Subarray Sums
class Solution {
public:
int rangeSum(vector<int>& nums, int n, int left, int right) {
const int MOD = 1'000'000'007;
vector<int> sums;
sums.reserve(n * (n + 1) / 2);
for (int i = 0; i < n; ++i) {
int s = 0;
for (int j = i; j < n; ++j) {
s += nums[j];
sums.push_back(s);
}
}
sort(sums.begin(), sums.end());
long ans = 0;
for (int i = left - 1; i < right; ++i) ans = (ans + sums[i]) % MOD;
return (int)ans;
}
};

Editorial#

Even at n = 1000, the sum list size is bounded by 500500 and fits in memory. Sorting and slicing is straightforward; the running prefix avoids re-summing inner subarrays.

Complexity#

  • Time: O(n^2 log n).
  • Space: O(n^2).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.