![]() |
VOOZH | about |
Given an array arr[] of N integers, your task is to process Q queries of the form: what is the sum of values in range [a,b]?
Examples
Input: arr[] = {1, 3, 4, 8, 6, 1, 4, 2}, Queries: {{2, 5}, {1, 3}}
Output: 21 8
Explanation:
- Query 1: Sum of elements from index 2 to 5 = 3 + 4 + 8 + 6 = 21
- Query 2: Sum of elements from index 1 to 3 = 1 + 3 + 4 = 8
Input: arr[] = {3, 2, 4, 5, 1, 1, 5, 3} Queries: {{2, 4}, {5, 6}, {1, 8}, {3, 3}}
Output: 11 2 24 4
Explanation:
- Query 1: Sum of elements from position 2 to 4 = 2 + 4 + 5 = 11
- Query 2: Sum of elements from position 5 to 6 = 1 + 1 = 2
- Query 3: Sum of elements from position 1 to 8 = 3 + 2 + 4 + 5 + 1 + 1 + 5 + 3 = 24
- Query 4: Sum of elements from position 3 to 3 = 4
Algorithm: To solve the problem, follow the below idea:
We can solve this problem using Prefix Sum approach.
- Pre-processing: Compute prefix sums for the array.
- Query Processing: Find the sum of the elements between the range l and r , i.e. prefixSum[r] - prefixSum[l-1].
Step-by-step algorithm:
Below is the implementation of the algorithm:
11 2 24 4
Time Complexity : O(N + Q), where N is the number of elements in arr[] and Q is the number of queries.
Auxiliary Space: O(N)