Last Updated: 16 Sep, 2021

Range Sum

Moderate
Asked in companies
AdobeMicrosoftGeeksforGeeks

Problem statement

You are given an array ‘arr’ of size ‘N’. You are provided with ‘Q’ queries, each containing two integers, ‘L’ and ‘R’. Your task is to return the sum of elements from the position ‘L’ to ‘R’ for each query.

For example:
You are given arr = [1, 3, 4, 5, 6, 9], and queries = [[1, 3], [5, 6] , [1, 6]].

For the first query [1, 3] sum of elements = 1 + 3 + 4 = 8. Hence the answer is 8

For the second query [5, 6] sum of elements = 6 + 9 = 15. Hence the answer is 15

For the third query [1, 6] sum of elements = 1 + 3 + 4 + 5 + 6 + 9= 28. Hence the answer is 28. 

Hence the final answer is [8, 15, 28]
Input Format:
The first line contains an integer 'T' which denotes the number of test cases.

The first line of each test case contains two space-separated integers, ‘N’ and ‘Q’, denoting the size of the array and the number of queries.

The second line contains ‘N’ space-separated integers representing the elements of the array ‘arr’.

The next ‘Q’ lines contain two space-separated integers, ‘L’ and ‘R’ representing each query.
Output Format:
For each test case, print ‘Q’ space-separated integers, denoting the sum of elements for each query.

The output of each test case will be printed in a separate line.
Constraints:
1 <= T <= 10 
1 <= N, Q <= 10 ^ 6
0 <= arr[i] <= 10 ^ 8
1 <= L <=  R <= N

Time limit: 1 sec
Note:
You do not need to input or print anything, as it has already been taken care of. Just implement the given function.

Approaches

01 Approach

In this approach, we will maintain an array, and for each query, we will take the sum from range L to R and store the sum in the array.

 

Algorithm:

  • Initialise an empty array ans.
  • Iterate query through the queries array
    • Set rSum as 0
    • Iterate i from query[0] - 1 to query[1] - 1
      • Add arr[i] to rSum
    • Insert rSum into the array arr
  • Finally, return arr

02 Approach

In this approach, we will create a prefix sum array, where the ith element stores the sum from 1 to ith position, therefore to find the sum of any range L to R we can find sum from 1 to L - 1 and sum from 1 to R and subtract the two to get the sum from range L to R.
 

Algorithm:

  • Create an array prefixSum of size N + 1 with initial values as 0
  • Iterate i from 1 to size of arr + 1
    • Set prefixSum[i] as sum of prefixSum[i - 1] + arr[i - 1]
  • Create an empty array ans
  • Iterate query through queries
    • Insert prefixSum[query[1]] - prefixSum[query[0] - 1] in ans
  • Finally, return the ans array.