710023. Compute Before Matrix

Medium

Compute Before Matrix

Summary

Given a matrix, compute all prefix sums along each row and column. The problem involves manipulating a 2D array to store cumulative sums for both rows and columns.

Detailed Explanation

To solve this problem, we can use a simple algorithm that iterates through the matrix and calculates the prefix sum for each row and column. We start by initializing an empty 2D array prefix_sum with the same dimensions as the input matrix. Then, we iterate through each element of the original matrix, adding it to the corresponding row and column in prefix_sum.

Here's a step-by-step breakdown:

  1. Initialize prefix_sum with zeros.
  2. Iterate through each element (i, j) in the original matrix:
    • Add the current element to the i-th row of prefix_sum.
    • Add the current element to the j-th column of prefix_sum.
  3. Return prefix_sum.

The time complexity for this algorithm is O(m * n), where m and n are the number of rows and columns in the matrix, respectively. The space complexity is also O(m * n) because we need to store the prefix sums.

Optimized Solutions

Java

View on GeeksforGeeks
public int[][] computeBeforeMatrix(int[][] matrix) {
    int m = matrix.length;
    int n = matrix[0].length;
    int[][] prefix_sum = new int[m][n];

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            prefix_sum[i][j] += matrix[i][j];
            if (i > 0) {
                prefix_sum[i][j] += prefix_sum[i - 1][j];
            }
            if (j > 0) {
                prefix_sum[i][j] += prefix_sum[i][j - 1];
            }
        }
    }

    return prefix_sum;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.