← Home

1508. Range Sum of Sorted Subarray Sums

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
heap / priority queueC++Markdown
150

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1508. Range Sum of Sorted Subarray Sums, the solution in this repository is mainly a heap / priority queue solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: heap / priority queue, two pointers, greedy.

The notes already sitting in the source point us in the right direction:

  • brute force

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are rangeSum.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The queue gives the solution a level-by-level or frontier-style traversal.
  • The heap keeps the best candidate available without sorting the whole world every time.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//brute force
02//Runtime: 640 ms, faster than 14.29% of C++ online submissions for Range Sum of Sorted Subarray Sums.
03//Memory Usage: 19.1 MB, less than 100.00% of C++ online submissions for Range Sum of Sorted Subarray Sums.
04class Solution {
05public:
06    int rangeSum(vector<int>& nums, int n, int left, int right) {
07        int MOD = 1e9+7;
08        
09        vector<int> subsums;
10        
11        for(int i = 0; i < n; ++i){
12            int cursum = nums[i];
13            subsums.push_back(cursum);
14            for(int j = i+1; j < n; ++j){
15                cursum += nums[j];
16                subsums.push_back(cursum);
17            }
18        }
19        
20        sort(subsums.begin(), subsums.end());
21        
22        return accumulate(subsums.begin()+(left-1), subsums.begin()+right, 0, [&MOD](int& a, int& b){return (a+b) % MOD;});
23    }
24};
25
26//priority_queue
27//https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/discuss/730511/C%2B%2B-priority_queue-solution
28//Runtime: 8 ms, faster than 100.00% of C++ online submissions for Range Sum of Sorted Subarray Sums.
29//Memory Usage: 8 MB, less than 100.00% of C++ online submissions for Range Sum of Sorted Subarray Sums.
30class Solution {
31public:
32    int rangeSum(vector<int>& nums, int n, int left, int right) {
33        //the smaller the earlier to be popped
34        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
35        
36        int MOD = 1e9+7;
37        
38        for(int i = 0; i < n; ++i){
39            //p.second: the index of next element to be appended to subarray
40            pq.push({nums[i], i+1});
41        }
42        
43        int ans = 0;
44        
45        for(int i = 1; i <= right; ++i){
46            //stop when we see "right" smallest subarrays' sums
47            
48            pair<int, int> p = pq.top(); pq.pop();
49            
50            if(i >= left){
51                //we want the [left, right]th subarray's sum(1-based)
52                ans = (ans + p.first) % MOD;
53            }
54            
55            if(p.second < n){
56                pq.push({p.first+nums[p.second++], p.second});
57            }
58        }
59        
60        return ans;
61    }
62};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.