Skip to main content

Solving the Prefix Sum Problem Using JavaScript

Solving the Prefix Sum Problem Using JavaScript

The prefix sum technique is a powerful approach to solving problems related to arrays, where we need to efficiently calculate the sum of elements up to a certain index. This method involves creating a new array, where each element at index i represents the sum of elements from the start of the array up to index i in the original array.

In this article, we will explore how to solve a typical problem using the prefix sum technique in JavaScript. We'll go through the steps, explain the approach, and show how to implement it.


1. Understanding the Prefix Sum Concept

The prefix sum array is created from an original array by iterating through each element and calculating the cumulative sum.

Example:

Given an array:

[1, 2, 3, 4, 5]

The prefix sum array will be:

[1, 3, 6, 10, 15]

This is because:

  • The first element remains the same (1).
  • The second element is the sum of the first two elements (1 + 2 = 3).
  • The third element is the sum of the first three elements (1 + 2 + 3 = 6), and so on.

This transformation allows us to answer range sum queries efficiently.


2. Problem: Range Sum Query Using Prefix Sum

Suppose we are given an array of integers, and we need to calculate the sum of elements between indices i and j multiple times.

Using a brute-force approach, we would have to iterate through the array for each query, which can be inefficient for large arrays. However, we can use the prefix sum array to answer each query in constant time.

Approach:

  • Construct the prefix sum array.

  • For a range sum query between indices i and j, the result can be computed as:

prefix[j] - prefix[i-1]

If i == 0, the sum is simply prefix[j].


3. Step-by-Step Solution in JavaScript

Let's implement the solution in JavaScript. We will define two functions:

  • buildPrefixSum: This function will create the prefix sum array.
  • rangeSum: This function will compute the sum of elements between two indices using the prefix sum array.

Step 1: Building the Prefix Sum Array

functionbuildPrefixSum(arr) {
    const prefixSum = [];
    let sum = 0;
    for (let i = 0; i & lt; arr.length; i++) {
        sum += arr[i];
        prefixSum.push(sum);
    }
    return prefixSum;
}

Explanation:

  • We iterate through the input array and maintain a running sum (sum).
  • At each step, we add the running sum to the prefixSum array.

Step 2: Querying the Range Sum

functionrangeSum(prefixSum, i, j) {
    if (i === 0) {
        return prefixSum[j];
    } else {
        return prefixSum[j] - prefixSum[i - 1];
    }
}

Explanation:

  • If the query starts from index 0, we return prefixSum[j].
  • Otherwise, the sum from index i to j is the difference between prefixSum[j] and prefixSum[i-1].

4. Full Code Example

Here's the complete implementation:

// Function to build the prefix sum array
functionbuildPrefixSum(arr) {
    const prefixSum = [];
    let sum = 0;
    for (let i = 0; i & lt; arr.length; i++) {
        sum += arr[i];
        prefixSum.push(sum);
    }
    return prefixSum;
}
// Function to get the range sum from index i to j
functionrangeSum(prefixSum, i, j) {
    if (i === 0) {
        return prefixSum[j];
    } else {
        return prefixSum[j] - prefixSum[i - 1];
    }
}
// Example usage:
const arr = [1, 2, 3, 4, 5];
const prefixSum = buildPrefixSum(arr);
console.log(rangeSum(prefixSum, 0, 2)); // Sum of elements from index 0 to 2: 6 (1 + 2 + 3)
console.log(rangeSum(prefixSum, 2, 4)); // Sum of elements from index 2 to 4: 12 (3 + 4 + 5)
console.log(rangeSum(prefixSum, 1, 3)); // Sum of elements from index 1 to 3: 9 (2 + 3 + 4)

Explanation:

6
12
9

Explanation:

  • The first query asks for the sum of elements from index 0 to 2, which is 1 + 2 + 3 = 6.
  • The second query asks for the sum from index 2 to 4, which is 3 + 4 + 5 = 12.
  • The third query asks for the sum from index 1 to 3, which is 2 + 3 + 4 = 9.

5. Time and Space Complexity Analysis

  • Time Complexity:

    • Building the prefix sum array takes O(n) time, where n is the size of the input array.
    • Each range sum query can be answered in O(1) time, thanks to the prefix sum array.
    • Thus, the overall time complexity for q queries is O(n + q).
  • Space Complexity:

    • The space complexity is O(n) because we store the prefix sum array.

6. Conclusion

The prefix sum technique is a powerful way to efficiently answer range sum queries. By building a prefix sum array, we can reduce the time complexity of each query to constant time, making it much faster than a brute-force solution. This technique is widely used in many algorithms, especially when dealing with range queries or cumulative sums.

In this article, we demonstrated how to use the prefix sum technique in JavaScript with a practical example and provided a detailed explanation of its implementation. This approach is highly effective in problems that require frequent sum calculations over subarrays.

Comments