Introduction
The Range Sum Query problem involves finding the sum of elements between two indices in an array.
Given an array arr[] and multiple queries (left,rigjt), the task is to calculate the sum of elements from index left to index right.
This is one of the most important Prefix Sum problems and helps in understanding preprocessing techniques, range queries, and efficient repeated computations.
Example
Input: arr[] = [2, 4, 1, 6, 3]Query:
left = 1
right = 3
Output: 11
Explanation:
Elements from index 1 to 3 are:
[4, 1, 6]
Sum = 4 + 1 + 6 = 11
Input: arr[] = [5, 2, 7, 1, 4]
Query:
left = 0
right = 2
Output: 14
Explanation:
Elements from index 0 to 2 are:
[5, 2, 7]
Sum = 14
- Constraints
1 <= n <= 10^5-10^9 <= arr[i] <= 10^9
0 <= left <= right < n
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Traverse elements from left to right.
- Add all elements
- Return the sum
This approach works but becomes inefficient when multiple queries are present.
Steps
- Initialize sum = 0.
- Traverse from index left to right.
- Add every element into sum.
- Return final sum.
Dry Run
Input Array: [2, 4, 1, 6, 3]left = 1
right = 3
Traverse index 1:
Sum = 4
Traverse index 2:
Sum = 4 + 1 = 5
Traverse index 3:
Sum = 5 + 6 = 11
Final Result:
11
Brute Force Code
Complexity Analysis
Time Complexity: O(n)Explanation:
Elements between left and right indices are traversed.
Space Complexity: O(1)
Explanation:
No extra data structures are used.
Approach 2 : Optimized Solution (Prefix Sum)
Explanation
Instead of recalculating sums for every query, we can preprocess the array using a Prefix Sum Array.
The idea is:
- Prefix Sum at index i stores:
- sum of elements from 0 to i.
- Range Sum can then be calculated using:
Range Sum = prefix[right] - prefix[left - 1]
This allows queries to be answered in constant time.
Steps
- Create prefix sum array.
- Store cumulative sums.
- For query:
- if left == 0:
- answer = prefix[right]
- otherwise:
- answer = prefix[right] - prefix[left - 1]
- if left == 0:
This becomes inefficient for multiple queries.
Dry Run
Input Array: [2, 4, 1, 6, 3]Build Prefix Sum Array:
prefix[0] = 2
prefix[1] = 2 + 4 = 6
prefix[2] = 6 + 1 = 7
prefix[3] = 7 + 6 = 13
prefix[4] = 13 + 3 = 16
Prefix Array:
[2, 6, 7, 13, 16]
Query:
left = 1
right = 3
Range Sum:
prefix[3] - prefix[0]
13 - 2 = 11
Final Result:
11
Optimized Code