← Home

303. Range Sum Query - Immutable

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
data structure designC++Markdown
303

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 303. Range Sum Query - Immutable, the solution in this repository is mainly a data structure design 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: data structure design.

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

  • Brute Force
  • query time: O(n), space: O(1)

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 sumRange.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • 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. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

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)

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Brute Force
02//query time: O(n), space: O(1)
03//Runtime: 176 ms, faster than 15.17% of C++ online submissions for Range Sum Query - Immutable.
04//Memory Usage: 17.3 MB, less than 72.41% of C++ online submissions for Range Sum Query - Immutable.
05class NumArray {
06public:
07    vector<int> nums;
08    
09    NumArray(vector<int>& nums) {
10        this->nums = nums;
11    }
12    
13    int sumRange(int i, int j) {
14        int ans = 0;
15        for(int pos = i; pos <= j; pos++){
16            ans += nums[pos];
17        }
18        return ans;
19    }
20};
21
22/**
23 * Your NumArray object will be instantiated and called as such:
24 * NumArray* obj = new NumArray(nums);
25 * int param_1 = obj->sumRange(i,j);
26 */
27 
28//Cache
29//Runtime: 28 ms, faster than 94.08% of C++ online submissions for Range Sum Query - Immutable.
30//Memory Usage: 17.2 MB, less than 79.31% of C++ online submissions for Range Sum Query - Immutable.
31//acc_sum[0] is 0
32//acc_sum[k] is the cumulative sum for nums[0 ... k-1](inclusive)
33//pre-computation time: O(n), query time: O(1)
34//space: O(n)
35class NumArray {
36public:
37    vector<int> acc_sum;
38    
39    NumArray(vector<int>& nums) {
40        int N = nums.size();
41        this->acc_sum = vector<int>(N+1);
42        //for padding
43        this->acc_sum[0] = 0;
44        for(int i = 1; i <= N; i++){
45            this->acc_sum[i] = this->acc_sum[i-1] + nums[i-1];
46        }
47    }
48    
49    int sumRange(int i, int j) {
50        //convert i and j from 0-based to 1-based
51        return this->acc_sum[j+1] - this->acc_sum[i];
52    }
53};
54
55/**
56 * Your NumArray object will be instantiated and called as such:
57 * NumArray* obj = new NumArray(nums);
58 * int param_1 = obj->sumRange(i,j);
59 */

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)
Auxiliary state plus the answer structure where the problem requires one.