Range Sum of Sorted Subarray Sums (LeetCode 1508): Solution and Explanation

Medium
Array
Two Pointers
Binary Search
Sorting
Prefix Sum

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

  1. Write count_and_sum(x): slide a window over nums, shrinking from the left while the window sum exceeds x. After each right end j, add j - i + 1 to the count and the window's running total of subarray sums to the total.
  2. Write sum_of_first(k): binary search x between min(nums) and sum(nums) for the smallest value with count_and_sum(x).count >= k.
  3. With that x, sum_of_first(k) = total - x * (count - k).
  4. 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
  1. The answer is f(5) - f(0). The search range for the 5th smallest sum is 1 to 10.
  2. 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.
  3. mid = 3: only 1, 2, 3, 3 are <= 3, four sums, fewer than 5, so lo = 4.
  4. mid = 4: five sums (1, 2, 3, 3, 4) are <= 4, so hi = 4 and the search ends at x = 4.
  5. At x = 4 the count is exactly 5 with total 13, so f(5) = 13.
  6. 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)) % MOD
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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.