> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Range Sum of Sorted Subarray Sums

> Tested Python solution for LeetCode 1508 with 22 pytest cases. Generate a practice environment with lcpy.

LeetCode 1508, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Two Pointers](/catalog/topics/two-pointers), [Binary Search](/catalog/topics/binary-search), [Sorting](/catalog/topics/sorting), [Prefix Sum](/catalog/topics/prefix-sum). [View on LeetCode](https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/description/).

Generate this problem as a practice environment: tested reference solution, 22 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1508   # by problem number
lcpy gen -s range_sum_of_sorted_subarray_sums   # by problem name
```

## Problem

\<p>You are given the array \<code>nums\</code> consisting of \<code>n\</code> positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of \<code>n \* (n + 1) / 2\</code> numbers.\</p>

\<p>\<em>Return the sum of the numbers from index \</em>\<code>left\</code>\<em> to index \</em>\<code>right\</code> (\<strong>indexed from 1\</strong>)\<em>, inclusive, in the new array. \</em>Since the answer can be a huge number return it modulo \<code>10\<sup>9\</sup> + 7\</code>.\</p>

### Examples

```
Input: nums = [1,2,3,4], n = 4, left = 1, right = 5
Output: 13
Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.
```

```
Input: nums = [1,2,3,4], n = 4, left = 3, right = 4
Output: 6
Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
```

```
Input: nums = [1,2,3,4], n = 4, left = 1, right = 10
Output: 50
```

### Constraints

\<ul>
\<li>\<code>n == nums.length\</code>\</li>
\<li>\<code>1 \<= nums.length \<= 1000\</code>\</li>
\<li>\<code>1 \<= nums\[i] \<= 100\</code>\</li>
\<li>\<code>1 \<= left \<= right \<= n \* (n + 1) / 2\</code>\</li>
\</ul>

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/range_sum_of_sorted_subarray_sums/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/range_sum_of_sorted_subarray_sums/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n * log(sum(nums))) ~ O(n log n)
    # Space: O(1)
    def range_sum(self, nums: list[int], n: int, left: int, right: int) -> int:
        mod = 1_000_000_007

        def count_and_sum(target: int) -> tuple[int, int]:
            # Number of subarrays with sum <= target, plus the sum of those sums.
            count = 0
            total = 0
            window_sum = 0
            window_total = 0
            start = 0
            for end, value in enumerate(nums):
                window_sum += value
                window_total += value * (end - start + 1)
                while window_sum > target:
                    window_total -= window_sum
                    window_sum -= nums[start]
                    start += 1
                count += end - start + 1
                total += window_total
            return count, total

        def prefix_sum_of_sums(k: int) -> int:
            # Sum of the k smallest subarray sums.
            lo, hi = min(nums), sum(nums)
            while lo < hi:
                mid = (lo + hi) // 2
                count, _ = count_and_sum(mid)
                if count < k:
                    lo = mid + 1
                else:
                    hi = mid
            count, total = count_and_sum(lo)
            return total - lo * (count - k)

        return (prefix_sum_of_sums(right) - prefix_sum_of_sums(left - 1)) % mod
```

## Complexity

| Time | Space |
| - | - |
| O(n \* log(sum(nums))) \~ O(n log n) | O(1) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.