LeetCode - Range Sum Query Immutable Solution - The Coding Shala

Home >> LeetCode >> Range Sum Query Immutable

 In this post, we will learn how to solve LeetCode's Range Sum Query Immutable Problem and its solution in Java.

Range Sum Query Immutable Problem

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Implement the NumArray class: 
NumArray(int[] nums) Initializes the object with the integer array nums. int sumRange(int i, int j) Return the sum of the elements of the nums array in the range [i, j] inclusive (i.e., sum(nums[i], nums[i + 1], ... , nums[j])).

Example 1:
Input: ["NumArray", "sumRange", "sumRange", "sumRange"]
           [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
Output: [null, 1, -1, -3]

Practice this problem on LeetCode: (Click Here)

Range Sum Query - Immutable Java Solution

Approach 1:
First, make a sum array that contains sum till every index then return sum[j] - sum[i-1].

Java Program: 

class NumArray {

    int len;
    int[] sum;
    
    public NumArray(int[] nums) {
        this.len = nums.length;
        sum = new int[len];
        for(int i=0;i<len;i++){
            if(i==0) sum[0] = nums[0];
            else sum[i] = nums[i] + sum[i-1];
        }
    }
    
    public int sumRange(int i, int j) {
        if(i==0) return sum[j];
        return (sum[j]-sum[i-1]);
    }
}

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


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala