# Range Sum Query - Immutable

This page explains Java solution to problem `Range Sum Query - Immutable` using `Prefix array`.

## Problem Statement

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

Example 1:

Input: nums = [-2, 0, 3, -5, 2, -1]
Output:
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

## Solution

If you have any suggestions in below code, please create a pull request by clicking here.
``````
package com.vc.easy;

class RangeSumQueryImmutable {
int[] prefixArr;
public RangeSumQueryImmutable(int[] nums) {
prefixArr = new int[nums.length + 1];
for(int i = 0; i < nums.length; i++) {
prefixArr[i + 1] = prefixArr[i] + nums[i];
}
}

public int sumRange(int i, int j) {
return prefixArr[j + 1] - prefixArr[i];
}
}

/**
* 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) to generate prefix sum array Where
N is total number of elements in an input array
O(1) to get range sum

## Space Complexity

O(N) Where
N is total number of elements in an input array