Blogs Hub

Range Sum Query - Immutable - Array - Easy - LeetCode

Range Sum Query - Immutable - Array - Easy - LeetCode

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
 

Constraints:

You may assume that the array does not change.
There are many calls to sumRange function.
0 <= nums.length <= 10^4
-10^5 <= nums[i] <= 10^5
0 <= i <= j < nums.length

public class NumArray {
    int[] sumArr;
    public NumArray(int[] nums) {
        if(nums.Length==0){
            return;
        }
        sumArr = new int[nums.Length];
        sumArr[0]=nums[0];
        for(int i=1;i<nums.Length;i++){
            sumArr[i]=sumArr[i-1]+nums[i];
        }
    }
    
    public int SumRange(int i, int j) {
        if(sumArr==null){
            return 0;
        }
        if(i==0){
            return sumArr[j];
        }
        return sumArr[j]-sumArr[i-1];
    }
}

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.SumRange(i,j);
 */

Time Complexity: O(n)

Space Complexity: O(n)