Range Sum Query - Immutable - Array - Easy - LeetCode
💻 coding

Range Sum Query - Immutable - Array - Easy - LeetCode

1 min read 148 words
1 min read
ShareWhatsAppPost on X
  • 1The problem involves calculating the sum of elements in an integer array between two indices, inclusive.
  • 2The solution uses a prefix sum array to efficiently compute the sumRange in constant time after an O(n) preprocessing step.
  • 3The constraints ensure the array remains unchanged, allowing multiple sumRange calls without recalculating the sums.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem involves calculating the sum of elements in an integer array between two indices, inclusive."

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)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 3 October 2020 · 1 min read · 148 words

Part of AskGif Blog · coding

You might also like