![]() |
VOOZH | about |
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.
Output
9
12
Follow the given steps to solve the problem:
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.