Range sum queries without updates

12 Jun, 2022
Given an array arr of integers of size n. We need to compute the sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times.
Examples: 
Input : arr[] = {1, 2, 3, 4, 5}
        i = 1, j = 3
        i = 2, j = 4
Output :  9
         12         

Input : arr[] = {1, 2, 3, 4, 5}
        i = 0, j = 4 
        i = 1, j = 2 
Output : 15
          5
A Simple Solution is to compute the sum for every query.
An Efficient Solution is to precompute prefix sum. Let pre[i] stores sum of elements from arr[0] to arr[i]. To answer a query (i, j), we return pre[j] – pre[i-1].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// CPP program to find sum between two indexes// when there is no update.#include <bits/stdc++.h>using namespace std; void preCompute(int arr[], int n, int pre[]){    pre[0] = arr[0];    for (int i = 1; i < n; i++)        pre[i] = arr[i] + pre[i - 1];} // Returns sum of elements in arr[i..j]// It is assumed that i <= jint rangeSum(int i, int j, int pre[]){    if (i == 0)        return pre[j];     return pre[j] - pre[i - 1];} // Driver codeint main(){    int arr[] = { 1, 2, 3, 4, 5 };    int n = sizeof(arr) / sizeof(arr[0]);     int pre[n];       // Function call    preCompute(arr, n, pre);    cout << rangeSum(1, 3, pre) << endl;    cout << rangeSum(2, 4, pre) << endl;     return 0;}
// Java program to find sum between two indexes// when there is no update. import java.util.*;import java.lang.*; class GFG {    public static void preCompute(int arr[], int n,                                  int pre[])    {        pre[0] = arr[0];        for (int i = 1; i < n; i++)            pre[i] = arr[i] + pre[i - 1];    }     // Returns sum of elements in arr[i..j]    // It is assumed that i <= j    public static int rangeSum(int i, int j, int pre[])    {        if (i == 0)            return pre[j];         return pre[j] - pre[i - 1];    }     // Driver code    public static void main(String[] args)    {        int arr[] = { 1, 2, 3, 4, 5 };        int n = arr.length;         int pre[] = new int[n];         preCompute(arr, n, pre);        System.out.println(rangeSum(1, 3, pre));        System.out.println(rangeSum(2, 4, pre));    }} // Code Contributed by Mohit Gupta_OMG <(0_o)>
# Python program to find sum between two indexes# when there is no update. # Function to compute prefix sumdef preCompute(arr, n, prefix):  prefix[0] = arr[0]  for i in range(1, n):    prefix[i] = prefix[i - 1] + arr[i] # Returns sum of elements in arr[i..j]# It is assumed that i <= jdef rangeSum(l, r):  if l == 0:    print(prefix[r])    return     print(prefix[r] - prefix[l - 1])     # Driver codearr = [1, 2, 3, 4, 5]n = len(arr)prefix = [0 for i in range(n)] # preComputationpreCompute(arr, n, prefix) # Range QueriesrangeSum(1, 3)rangeSum(2, 4) # This code is contributed by dineshdkda31.
// Program to find sum between two// indexes when there is no update.using System; class GFG {    public static void preCompute(int[] arr, int n,                                  int[] pre)    {        pre[0] = arr[0];        for (int i = 1; i < n; i++)            pre[i] = arr[i] + pre[i - 1];    }     // Returns sum of elements in    // arr[i..j]    // It is assumed that i <= j    public static int rangeSum(int i, int j, int[] pre)    {        if (i == 0)            return pre[j];         return pre[j] - pre[i - 1];    }     // Driver code    public static void Main()    {        int[] arr = { 1, 2, 3, 4, 5 };        int n = arr.Length;         int[] pre = new int[n];         // Function call        preCompute(arr, n, pre);        Console.WriteLine(rangeSum(1, 3, pre));        Console.WriteLine(rangeSum(2, 4, pre));    }} // Code Contributed by Anant Agarwal.
<script> // JavaScript Program to find sum between two// indexes when there is no update. let pre = new Array(1000,0); function preCompute(arr, n){    pre[0] = arr[0];    for (let i = 1; i < n; i++)        pre[i] = arr[i] + pre[i - 1];} // Returns sum of elements in// arr[i..j]// It is assumed that i <= jfunction rangeSum(i, j, pre){    if (i == 0)        return pre[j];     return pre[j] - pre[i - 1];} // Driver codelet arr = [1, 2, 3, 4, 5];let n = arr.length;   // Function callpreCompute(arr, n); document.write(rangeSum(1, 3, pre)+"<br>");document.write(rangeSum(2, 4, pre)); </script>
9
12
Here time complexity of every range sum query is O(1) and the overall time complexity is O(n).
Auxiliary Space required = O(n), where n is the size of the given array.
The question becomes complicated when updates are also allowed. In such situations when using advanced data structures like Segment Tree or Binary Indexed Tree.
This article is contributed by Rahul Chawla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
deepak atariya
mohit kumar 29
dineshdkda31
tamanna17122007
array-range-queries
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Introduction to Data Structures