Partial sum in array of arrays JavaScript

In the given problem statement our task is to get the partial sum in an array of arrays with the help of JavaScript functionalities. The partial sum at position (i, j) represents the sum of all elements from the top-left corner (0, 0) to the current position (i, j).

Understanding the Problem

An array of arrays (2D array) is a data structure where each element is itself an array. For example:

[
   [1, 2, 3],
   [4, 5, 6], 
   [7, 8, 9]
]

The partial sum at position (i, j) is the sum of all elements in the rectangle from (0, 0) to (i, j). This is also known as a prefix sum or cumulative sum in a 2D array.

Algorithm

Step 1: Create a function to compute partial sums and handle edge cases for empty arrays.

Step 2: Initialize a 2D result array with the same dimensions as the input.

Step 3: For each position (i, j), calculate the partial sum using previously computed values:

  • If it's the top-left corner: partial_sum = current_element
  • If it's the first row: partial_sum = left_partial_sum + current_element
  • If it's the first column: partial_sum = top_partial_sum + current_element
  • Otherwise: partial_sum = top + left - top_left + current_element

Implementation

function sumOfSubarrays(arr) {
   if (arr.length === 0) return [];

   const numRows = arr.length;
   const numCols = arr[0].length;

   // Create a 2D array to store the partial sums
   const partialSums = new Array(numRows);
   for (let i = 0; i < numRows; i++) {
      partialSums[i] = new Array(numCols);
   }

   // Compute the partial sums
   for (let i = 0; i < numRows; i++) {
      for (let j = 0; j < numCols; j++) {
         if (i === 0 && j === 0) {
            // Top-left corner
            partialSums[i][j] = arr[i][j];
         } else if (i === 0) {
            // First row
            partialSums[i][j] = partialSums[i][j - 1] + arr[i][j];
         } else if (j === 0) {
            // First column
            partialSums[i][j] = partialSums[i - 1][j] + arr[i][j];
         } else {
            // General case: add top + left - diagonal + current
            partialSums[i][j] = partialSums[i - 1][j] + partialSums[i][j - 1] - partialSums[i - 1][j - 1] + arr[i][j];
         }
      }
   }

   return partialSums;
}

// Example usage
const array = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];

const result = sumOfSubarrays(array);
console.log("Original array:");
console.log(array);
console.log("Partial sums:");
console.log(result);
Original array:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Partial sums:
[ [ 1, 3, 6 ], [ 5, 12, 21 ], [ 12, 27, 45 ] ]

How It Works

Let's trace through the calculation for position (2, 2) with value 9:

  • Top: partialSums[1][2] = 21
  • Left: partialSums[2][1] = 27
  • Diagonal: partialSums[1][1] = 12
  • Current: arr[2][2] = 9
  • Result: 21 + 27 - 12 + 9 = 45

Alternative Approach: Row-wise Calculation

function partialSumSimple(arr) {
   if (arr.length === 0) return [];
   
   const result = arr.map(row => [...row]); // Create a copy
   
   // Calculate partial sums row by row
   for (let i = 0; i < result.length; i++) {
      for (let j = 0; j < result[i].length; j++) {
         if (i > 0) result[i][j] += result[i - 1][j]; // Add from above
         if (j > 0) result[i][j] += result[i][j - 1]; // Add from left
         if (i > 0 && j > 0) result[i][j] -= result[i - 1][j - 1]; // Subtract overlap
      }
   }
   
   return result;
}

// Test with same example
const testArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
console.log(partialSumSimple(testArray));
[ [ 1, 3, 6 ], [ 5, 12, 21 ], [ 12, 27, 45 ] ]

Complexity Analysis

Aspect Complexity Explanation
Time O(m × n) Visit each element once
Space O(m × n) Store result array of same size

Where m is the number of rows and n is the number of columns in the input array.

Conclusion

Computing partial sums in a 2D array uses dynamic programming principles, where each position builds upon previously calculated values. This technique is fundamental for range sum queries and has applications in image processing and computational geometry.

Updated on: 2026-03-15T23:19:00+05:30

346 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements