![]() |
VOOZH | about |
Prefix Sum is used to solve problems involving the sum of elements between two indices in an array or operations on subarrays.
Using the prefix sum technique,
Prefix: In general terms, a prefix of a sequence is a part of the sequence that starts from the first element and extends up to a certain position. For an array, the prefix ending at index i includes all elements from index 0 to i.
Prefix Sum: A prefix sum is the cumulative sum of elements of an array from the beginning up to a given index. It represents the total of all elements from index 0 to i.
For a query that asks for the sum of elements in the range [L, R] in an array, the result can be obtained by subtracting the prefix sum at index L − 1 from the prefix sum at index R. If L = 0, then the sum is simply equal to prefix[R].
Let the original array be: arr[] = [a0, a1, a2, ..., an-i].
The prefix sum array is: prefix[i] = a0 + a1 + a2 + ... + ai
So,
Now if we want to calculate the sum from range l to r, we know
Sum(0, r) = prefix[r] and Sum(0, l − 1) = prefix[l − 1].
So now, Sum(l, r) = prefix[r] − prefix[l − 1], and we can easily calculate this in constant time.
Given an array arr[] of integers and a list of queries queries[][], where each query is in the form [L, R], compute the sum of elements from index L to R (both inclusive) for each query.
Example:
Input: arr[] = [2, 4, 6, 8, 10], queries[][] = [[1, 3], [0, 2]]
Output: [18, 12]
Explanation:
Query [1, 3] → 4 + 6 + 8 = 18
Query [0, 2] → 2 + 4 + 6 = 12Input: arr[] = [5, 1, 3, 2], queries[][] = [[0, 1], [2, 3]]
Output: [6, 5]
Explanation:
Query [0, 1] → 5 + 1 = 6
Query [2, 3] → 3 + 2 = 5
Solution :Array Range Sum Solution