Range Sum of Sorted Subarray Sums - Problem

You are given an array nums consisting of n positive integers. You need to compute the sum of all non-empty continuous subarrays from the array and then sort them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.

Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4], left = 1, right = 5
Output: 13
💡 Note: All subarray sums: [1]=1, [2]=2, [3]=3, [4]=4, [1,2]=3, [2,3]=5, [3,4]=7, [1,2,3]=6, [2,3,4]=9, [1,2,3,4]=10. Sorted: [1,2,3,3,4,5,6,7,9,10]. Sum from index 1 to 5: 1+2+3+3+4 = 13
Example 2 — Small Array
$ Input: nums = [1,2], left = 1, right = 3
Output: 6
💡 Note: Subarray sums: [1]=1, [2]=2, [1,2]=3. Sorted: [1,2,3]. Sum from index 1 to 3: 1+2+3 = 6
Example 3 — Single Range
$ Input: nums = [1,2,3,4], left = 1, right = 10
Output: 50
💡 Note: All 10 subarray sums: [1,2,3,3,4,5,6,7,9,10]. Sum of all elements: 1+2+3+3+4+5+6+7+9+10 = 50

Constraints

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

Visualization

Tap to expand
Range Sum of Sorted Subarray Sums INPUT nums array: 1 [0] 2 [1] 3 [2] 4 [3] All Subarray Sums: [1]=1 [2]=2 [3]=3 [4]=4 [1,2]=3 [2,3]=5 [3,4]=7 [1,2,3]=6 [2,3,4]=9 [1,2,3,4]=10 Parameters: left = 1, right = 5 (1-indexed positions) Total: n*(n+1)/2 = 10 sums ALGORITHM STEPS 1 Init Priority Queue Min-heap with (sum, end_idx) PQ: [(1,0),(2,1), (3,2),(4,3)] 2 Extract Minimum Pop smallest sum each time 3 Extend Subarray Add next element, push back Sorted extraction order: 1, 2, 3, 3, 4, 5, 6, 7, 9, 10 (positions 1-10) 4 Sum Range [left,right] Accumulate sums in range 1+2+3+3+4 = 13 FINAL RESULT Sorted Subarray Sums: 1 2 3 3 4 5 6 7 9 10 1 2 3 4 5 Range [1, 5] highlighted Calculation: 1 + 2 + 3 + 3 + 4 = 13 OUTPUT 13 OK - Result verified! Key Insight: The Priority Queue approach efficiently generates sorted subarray sums without storing all n*(n+1)/2 values. By using a min-heap initialized with single elements, we can extend subarrays on-the-fly and extract sums in sorted order. Time: O(n^2 * log n), Space: O(n) - much better than sorting all sums! TutorialsPoint - Range Sum of Sorted Subarray Sums | Priority Queue Approach
Asked in
Google 12 Amazon 8 Microsoft 6
28.5K Views
Medium Frequency
~35 min Avg. Time
742 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen