VOOZH about

URL: https://www.geeksforgeeks.org/dsa/compute-before-matrix/

⇱ Compute Matrix before Given Operations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Compute Matrix before Given Operations

Last Updated : 27 Feb, 2026

There are two matrices, before[][] and after[][] of size N×M. The matrix after[][] is obtained by applying the 2D prefix sum operation on before[][]. Given the matrix after[][], reconstruct the original matrix before[][].

Examples:

Input:  N = 2, M = 3, after[][] = [ [1, 3, 6], [3, 7, 11] ]
Output:
1 2 3
2 2 1
Explanation: The before matrix for the given after matrix is [ [1, 2, 3], [2, 2, 1] ].
Because according to the code given in problem, 
after(0, 0) = before(0, 0) = 1
after(0, 1) = before(0, 0) + before(0, 1) = 1 + 2 = 3.
after(0, 2) = before(0, 0) + before(0, 1) + before(0, 2) = 1 + 2 + 3 = 6.
after(1, 0) = before(0, 0) + before(1, 0) = 1 + 2 = 3;, 
after(1, 1) = before(0, 0) + before(0, 1) + before(1, 0) + before(1, 1) = 1 + 2 + 2 + 2 = 7.
after(1, 2) = before(0, 0) + before(0, 1) + before(0, 2) + before(1, 0) + before(1, 1) + before(1, 2) = 1 + 2 + 3 + 2 + 2 + 1 = 11

Input: N = 1, M = 3, after[][] = [[1, 3, 5]]
Output:
1 2 2

[Approach] - Reconstruct the Matrix from 2D Prefix Sum O(n × m ) time and O(n × m ) space

Consider the opposite task, i.e. to convert before[][] matrix to after[][]. As seen from the problem statement, after[i][j] is the summation of all the cells to the left of jth column and all the rows above the ith row. That is basically the prefix sum of a matrix.  So this problem is mainly an extension of Original Array from given Prefix Sums

  • Using the 2D prefix sum formula: prefix[i][j] = arr[i][j] + prefix[i-1][j] + prefix[i][j-1] - prefix[i-1][j-1]
  • Rearranging the equation, we get: arr[i][j] = prefix[i][j] - prefix[i-1][j] - prefix[i][j-1] + prefix[i-1][j-1]

Output
1 2 3 
2 2 1 
Comment
Article Tags: