2 min read algorithm
Prefix Sum Approach in JavaScript
Optimizing Algorithms with Prefix Sum Approach in JavaScript
The Prefix Sum technique is an elegant approach in algorithm design, especially useful for handling arrays in JavaScript. It allows for the efficient computation of cumulative sums, making it an excellent choice for problems where multiple sum queries need to be answered efficiently.
Why Prefix Sum?
- Efficiency: Greatly improves performance, especially in scenarios requiring frequent sum calculations over a range of elements.
- Simplicity: Simplifies complex problems, reducing them to manageable levels with pre-computed cumulative sums.
- Versatility: Useful in array manipulations, ranging from sum queries to subarray computations.
Understanding the Basics:
The Prefix Sum technique involves creating an array that stores the cumulative sum of elements. This pre-computed array then allows for quick calculations of the sum of elements in any given range.
- Pre-Computation: Calculate the cumulative sum of the array elements and store it in a separate array.
- Query Resolution: Use the pre-computed sums to quickly calculate the sum of elements over any range.
Example: Sum of Range Query in an Array
Problem Statement:
Given an array, find the sum of elements between indices i and j (inclusive).
Solution Using Prefix Sum:
function createPrefixSumArray(arr) {
let prefixSum = new Array(arr.length);
prefixSum[0] = arr[0];
for (let i = 1; i < arr.length; i++) {
prefixSum[i] = prefixSum[i - 1] + arr[i];
}
return prefixSum;
}
function rangeSumQuery(prefixSum, i, j) {
if (i == 0) return prefixSum[j];
return prefixSum[j] - prefixSum[i - 1];
}
How the Code Works:
- Creating Prefix Sum Array: The
createPrefixSumArrayfunction computes the cumulative sum of the elements and stores it in theprefixSumarray. - Handling Range Sum Query: The
rangeSumQueryfunction quickly calculates the sum for any range using the pre-computedprefixSumarray. If the range starts from 0, it directly returns the value atjin theprefixSumarray. Otherwise, it calculates the sum by subtracting the cumulative sum up toi-1from the cumulative sum up toj. - Efficient Computation: This technique reduces the time complexity for each sum query to O(1), assuming the prefix sum array has been precomputed.