Logo

dev-resources.site

for different kinds of informations.

Range Sum Query - Immutable

Published at
1/2/2025
Categories
prefixsum
leetcode
dsa
Author
Prashant Mishra
Categories
3 categories in total
prefixsum
open
leetcode
open
dsa
open
Range Sum Query - Immutable

Problem
TC: O(n) for calculating the prefix sum and O(1) for getting the sum of the subarray in the range left and right

class NumArray {

    int prefix[];
    public NumArray(int[] nums) {
        prefix = new int[nums.length];
        int currentSum =0;
        for(int i=0;i<nums.length;i++){
            currentSum+=nums[i];
            prefix[i] = currentSum;
        }
    }

    public int sumRange(int left, int right) {
        int rightSum = prefix[right];
        int leftSum = (left>0) ? prefix[left-1]:0;
        return rightSum-leftSum;
    }
}

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

For calculating the sum of the subarray within left and right we can leverage the prefix sum, each prefix[i] tell the sum till ith index from the starting index 0, hence if we have to find the sum of subarray left and right (inclusive) can get the rightPrefixSum till right index( it will be from 0 to right index) and we can also get leftPrefixSum till left-1 (it will be from 0 to left-1 index) and finally when we do rightPrefixSum-leftPrefixSum we will get the sum of subarray between left and right pointer.

Featured ones: