dev-resources.site
for different kinds of informations.
Range Sum Query - Immutable
Published at
1/2/2025
Categories
prefixsum
leetcode
dsa
Author
Prashant Mishra
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.
Articles
12 articles in total
Minimize XOR
read article
Count prefix and suffix I and II
read article
Rabin Karp (hashing) String pattern matching
read article
Min no. of operations to move all balls to each box
read article
Find all anagrams in the string[Fixed Window pattern]
read article
No of ways to split Array
read article
Range sum query 2D - Immutable
read article
Count vowel strings in ranges
read article
Range Sum Query - Immutable
currently reading
Job Scheduling Problem with Max Profit
read article
Non overlapping intervals
read article
Minimum No. of arrows to burst balloons
read article
Featured ones: