![]() |
VOOZH | about |
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 = 11Input: N = 1, M = 3, after[][] = [[1, 3, 5]]
Output:
1 2 2
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
prefix[i][j] = arr[i][j] + prefix[i-1][j] + prefix[i][j-1] - prefix[i-1][j-1] arr[i][j] = prefix[i][j] - prefix[i-1][j] - prefix[i][j-1] + prefix[i-1][j-1]1 2 3 2 2 1