Given an array arr of integers of size n. We need to compute 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 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].
CPP
// 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 <= j int rangeSum(int i, int j, int pre[]) { if (i == 0) return pre[j]; return pre[j] - pre[i-1]; } // Driver code int main() { int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr)/sizeof(arr[0]); int pre[n]; preCompute(arr, n, pre); cout << rangeSum(1, 3, pre) << endl; cout << rangeSum(2, 4, pre) << endl; return 0; } |
Python3
# Python program to find sum between two indexes # when there is no update. def find_ans(ar, j, k): l = len(ar) for i in range(1, l): ar[i] = ar[i] + ar[i-1] print(ar[k] - ar[j-1]) return; pr = [1, 2, 3 ,4, 5] ar = pr[:] find_ans(ar, 1, 3) ar = pr[:] find_ans(ar, 2 ,4) # Code Contributed by Mohit Gupta_OMG <(0_o)> |
Java
// 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]; } 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)> |
C#
// 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]; preCompute(arr, n, pre); Console.WriteLine(rangeSum(1, 3, pre)); Console.WriteLine(rangeSum(2, 4, pre)); } } // Code Contributed by Anant Agarwal. |
Output:
9 12
Here time complexity of every range sum query is O(1).
The question becomes complicated when updates are also allowed. In such situations when use 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 contribute.geeksforgeeks.org or mail your article to contribute@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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Dynamic Segment Trees : Online Queries for Range Sum with Point Updates
- Modified Range Sum in a given Array without updates
- Binary Indexed Tree : Range Updates and Point Queries
- Queries to find maximum product pair in range with updates
- Array range queries to count the number of Fibonacci numbers with updates
- Array Range Queries to count Powerful numbers with updates
- Range Queries to count the number of even parity values with updates
- Array range queries to find the maximum Fibonacci number with updates
- Array range queries to find the number of perfect square elements with updates
- Range Queries for number of Armstrong numbers in an array with updates
- String Range Queries to count number of distinct characters with updates
- Queries for count of array elements with values in given range with updates
- Queries to find Kth greatest character in a range [L, R] from a string with updates
- Array Range Queries to find the Maximum Armstrong number with updates
- Array range queries over range queries
- Queries to find the Lower Bound of K from Prefix Sum Array with updates using Fenwick Tree
- Queries for Composite numbers in subarray (With Point Updates)
- Queries to count array elements greater than or equal to a given number with updates
- Queries to replace every array element by its XOR with a given value with updates
- XOR of elements in a given range with updates using Fenwick Tree

