Range Sum of Sorted Subarray Sums (LeetCode 1508): Solution and Explanation
Take every contiguous subarray sum of a positive array, sort them, and add up positions left through right. With nums = [1,2,3,4], left = 1 and right = 5 the sorted sums are [1,2,3,3,4,5,6,7,9,10] and the first five add up to 13.
Intuition
A range of positions in a sorted list is the difference of two prefixes: positions left..right add up to f(right) - f(left - 1), where f(k) is the sum of the k smallest values. So it is enough to compute the sum of the k smallest subarray sums.
Listing all n(n + 1)/2 sums is what we want to avoid. Instead, ask a yes or no question about a value x: how many subarray sums are at most x? Because every number is positive, the subarrays ending at j with sum <= x are exactly those starting at some i or later, and i only moves right as j grows. A sliding window answers the question in one pass.
The same window can also keep the total of those sums. When j joins, each of the j - i + 1 subarrays ending at j gains nums[j]; when i leaves, the subarray nums[i..j] drops out. So one pass returns both the count and the total.
The count grows with x, so binary search finds the smallest x whose count reaches k: that is the k-th smallest sum. All sums below x are in the first k, and so are some copies of x. If the count overshoots k, the extra count - k copies each equal x, so subtract x * (count - k).
Approach: Binary search on the value with a sliding-window count
- Write
count_and_sum(x): slide a window overnums, shrinking from the left while the window sum exceedsx. After each right endj, addj - i + 1to the count and the window's running total of subarray sums to the total. - Write
sum_of_first(k): binary searchxbetweenmin(nums)andsum(nums)for the smallest value withcount_and_sum(x).count >= k. - With that
x,sum_of_first(k) = total - x * (count - k). - Return
(sum_of_first(right) - sum_of_first(left - 1)) mod 1e9+7.
Step-by-step example
nums = [1,2,3,4], n = 4, left = 1, right = 5
- The answer is f(5) - f(0). The search range for the 5th smallest sum is 1 to 10.
- mid = 5: the window counts sums <= 5. They are 1, 2, 3, 3, 4, 5, six of them, which is at least 5, so hi = 5.
- mid = 3: only 1, 2, 3, 3 are <= 3, four sums, fewer than 5, so lo = 4.
- mid = 4: five sums (1, 2, 3, 3, 4) are <= 4, so hi = 4 and the search ends at x = 4.
- At x = 4 the count is exactly 5 with total 13, so f(5) = 13.
- f(0) comes out as 0, so the answer is 13 - 0 = 13.
Code: Python, Java, C++
1class Solution:
2 def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:
3 MOD = 10**9 + 7
4
5 def count_and_sum(target):
6 count = total = window = cur = 0
7 i = 0
8 for j in range(n):
9 cur += nums[j]
10 window += nums[j] * (j - i + 1)
11 while cur > target:
12 window -= cur
13 cur -= nums[i]
14 i += 1
15 count += j - i + 1
16 total += window
17 return count, total
18
19 def sum_of_first(k):
20 lo, hi = min(nums), sum(nums)
21 while lo < hi:
22 mid = (lo + hi) // 2
23 if count_and_sum(mid)[0] >= k:
24 hi = mid
25 else:
26 lo = mid + 1
27 count, total = count_and_sum(lo)
28 return total - lo * (count - k)
29
30 return (sum_of_first(right) - sum_of_first(left - 1)) % MOD1class Solution {
2 public int rangeSum(int[] nums, int n, int left, int right) {
3 final long MOD = 1_000_000_007L;
4 long ans = sumOfFirst(nums, right) - sumOfFirst(nums, left - 1);
5 return (int) (ans % MOD);
6 }
7
8 private long[] countAndSum(int[] nums, long target) {
9 long count = 0, total = 0, windowSum = 0, cur = 0;
10 int i = 0;
11 for (int j = 0; j < nums.length; j++) {
12 cur += nums[j];
13 windowSum += (long) nums[j] * (j - i + 1);
14 while (cur > target) {
15 windowSum -= cur;
16 cur -= nums[i];
17 i++;
18 }
19 count += j - i + 1;
20 total += windowSum;
21 }
22 return new long[] {count, total};
23 }
24
25 private long sumOfFirst(int[] nums, int k) {
26 long lo = Integer.MAX_VALUE, hi = 0;
27 for (int x : nums) {
28 lo = Math.min(lo, x);
29 hi += x;
30 }
31 while (lo < hi) {
32 long mid = (lo + hi) / 2;
33 if (countAndSum(nums, mid)[0] >= k) {
34 hi = mid;
35 } else {
36 lo = mid + 1;
37 }
38 }
39 long[] res = countAndSum(nums, lo);
40 return res[1] - lo * (res[0] - k);
41 }
42}1class Solution {
2public:
3 int rangeSum(vector<int>& nums, int n, int left, int right) {
4 const long long MOD = 1000000007LL;
5 long long ans = sumOfFirst(nums, right) - sumOfFirst(nums, left - 1);
6 return (int)(ans % MOD);
7 }
8
9private:
10 pair<long long, long long> countAndSum(vector<int>& nums, long long target) {
11 long long count = 0, total = 0, windowSum = 0, cur = 0;
12 int i = 0;
13 for (int j = 0; j < (int)nums.size(); j++) {
14 cur += nums[j];
15 windowSum += (long long)nums[j] * (j - i + 1);
16 while (cur > target) {
17 windowSum -= cur;
18 cur -= nums[i];
19 i++;
20 }
21 count += j - i + 1;
22 total += windowSum;
23 }
24 return {count, total};
25 }
26
27 long long sumOfFirst(vector<int>& nums, int k) {
28 long long lo = *min_element(nums.begin(), nums.end());
29 long long hi = accumulate(nums.begin(), nums.end(), 0LL);
30 while (lo < hi) {
31 long long mid = (lo + hi) / 2;
32 if (countAndSum(nums, mid).first >= k) {
33 hi = mid;
34 } else {
35 lo = mid + 1;
36 }
37 }
38 pair<long long, long long> res = countAndSum(nums, lo);
39 return res.second - lo * (res.first - k);
40 }
41};Time and space complexity
O(n log S)
S is the sum of nums. The binary search takes O(log S) steps and each counting pass is O(n), done for two values of k.
O(1)
Only the window pointers and a few running totals are stored.
Other approaches
Generate and sort every sum (time O(n^2 log n), space O(n^2))
Build all n(n + 1)/2 prefix-difference sums, sort them and add positions left..right. Short and accepted for n up to 1000.
Min-heap merge of rows (time O(right log n), space O(n))
Each start index i gives an increasing row of sums. Push the first sum of each row into a min-heap and pop right times, extending the popped row each time.
Common mistakes
- Forgetting that positions are 1-indexed, so the prefix to subtract is f(left - 1), not f(left).
- Not trimming the extra copies of the threshold value. When several sums equal x, the count can exceed k and the plain total is too large.
- Overflowing 32-bit integers in Java, C++, C# or Go. Totals reach about 5 * 10^10, so keep them in 64-bit and apply the modulo at the end.
- Using the sliding window on arrays that can contain zeros or negatives. It relies on every value being positive so the left edge never moves back.
Frequently asked questions
Why does the binary search land on an actual subarray sum?
It finds the smallest x whose count is at least k. If x were not a subarray sum, x - 1 would have the same count and would also qualify, which contradicts x being the smallest.
Is the modulo ever needed for the answer?
The largest possible total is around 5 * 10^10, which exceeds 10^9 + 7, so yes for big inputs. Compute in 64-bit and reduce once at the end.
Why compute f(left - 1) with a second search instead of reusing the first?
The two prefixes end at different values, so each needs its own threshold. Two searches of O(n log S) each are still far cheaper than sorting all the sums.