Compute Matrix before Given Operations
Last Updated :
18 Mar, 2025
For a given matrix before[][], the corresponding cell (x, y) of the after[][] matrix is calculated as follows:
res = 0;
for(i = 0; i <= x; i++){
for( j = 0; j <= y; j++){
res += before(i, j);
}
}
after(x, y) = res;
Given an n*m matrix after[][], your task is to find the corresponding before[][] matrix for the given matrix.
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: The problem can be solved based on the following observation:
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
Based on the above observation the problem can be solved with the help of the example as shown below:
Consider before[][] = { {1, 2, 3}, {2, 2, 1} }
before[][] matrixSee how this matrix is converted into after[][] matrix.
For (0, 0): after[0][0] = before[0][0] = 1
For (0, 1): after[0][1] = before[0][0] + before[0][1] = after[0][0] + before[0][1] = 1 + 2 = 3
For (0, 2): after[0][2] = before[0][0] + before[0][1] + before[0][2] = after[0][1] + before[0][2] = 3 + 3 = 6
For (1, 0): after[1][0] = before[0][0] + before[1][0] = after[0][0] + before[1][0] = 1 + 2 = 3
For (1, 1): after[1][1] = before[0][0] + before[0][1] + before[1][0] + before[1][1]
= before[0][0] + before[0][1] + before[0][0] + before[1][0] - before[0][0] + before[1][1]
= after[0][1] + after[1][0] - after[0][0] + before[1][1] = 3 + 3 - 1 + 2 = 7
For (1, 2): Similarly like the previous one
after[1][2] = after[0][2] + after[1][1] - after[0][1] + before[1][2] = 6 + 7 - 3 + 1 = 11
Note: In the procedure, if the value of i and j is non-zero then in that case while taking the values from up and left sides of i and j respectively, we have counted twice the value of the after[i-1][j-1].
Now from the above procedure only we are going to determine how to get the before[][] matrix when we have been given after[][] matrix
For the first cell (i=0, j=0): before[0][0] = after[0][0]
For the first row:
after[i][j] = after[i][j-1] + before[i][j] can be converted to before[i][j] = after[i][j] - after[i][j-1]
For the first column:
after[i][j] = after[i-1][j] + before[i][j] can be converted to before[i][j] = after[i][j] - after[i-1][j]
For the rest of the cell:
after[i][j] = after[i-1][j] + after[i][j-1] - after[i-1][j-1] + before[i][j] can be converted to before[i][j] = after[i][j] + after[i-1][j-1] - after[i-1][j] - after[i][j-1]
Follow the steps mentioned below to implement the approach:
- Iterate through all the cells (i, j) of the matrix:
- Check the values of (i, j) to determine the location of the cell.
- Based on the location, use one of the formulae shown above and determine the value of before[i][j].
- Return the before[][] matrix after the iteration is over.
Below is the implementation of the above approach.
C++
// C++ code to Compute before Matrix
#include <bits/stdc++.h>
using namespace std;
// Function to compute before matrix
vector<vector<int>> computeBeforeMatrix(vector<vector<int>>& after) {
int n = after.size(), m = after[0].size();
// Declaring a 2d array to store
// the values of the before Matrix
vector<vector<int>> before(n, vector<int>(m, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i == 0 && j == 0)
before[0][0] = after[0][0];
else if (i == 0)
before[i][j]
= after[i][j] - after[i][j - 1];
else if (j == 0)
before[i][j]
= after[i][j] - after[i - 1][j];
else
before[i][j]
= after[i][j] + after[i - 1][j - 1]
- after[i - 1][j] - after[i][j - 1];
}
}
// Return the before[][] matrix
return before;
}
int main() {
vector<vector<int>> after{ { 1, 3, 6 }, { 3, 7, 11 } };
vector<vector<int>> ans = computeBeforeMatrix(after);
for (auto u : ans) {
for (int x : u)
cout << x << " ";
cout << endl;
}
return 0;
}
Java
// Java code to Compute before Matrix
class GfG {
// Function to compute before matrix
static int[][] computeBeforeMatrix(int[][] after) {
int n = after.length, m = after[0].length;
// Declaring a 2D array to store
// the values of the before Matrix
int[][] before = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i == 0 && j == 0)
before[0][0] = after[0][0];
else if (i == 0)
before[i][j] = after[i][j] - after[i][j - 1];
else if (j == 0)
before[i][j] = after[i][j] - after[i - 1][j];
else
before[i][j] = after[i][j] + after[i - 1][j - 1]
- after[i - 1][j] - after[i][j - 1];
}
}
// Return the before[][] matrix
return before;
}
public static void main(String[] args) {
int[][] after = { { 1, 3, 6 }, { 3, 7, 11 } };
int[][] ans = computeBeforeMatrix(after);
for (int[] row : ans) {
for (int x : row)
System.out.print(x + " ");
System.out.println();
}
}
}
Python
# Python code to Compute before Matrix
# Function to compute before matrix
def computeBeforeMatrix(after):
n, m = len(after), len(after[0])
# Declaring a 2D list to store
# the values of the before Matrix
before = [[0] * m for _ in range(n)]
for i in range(n):
for j in range(m):
if i == 0 and j == 0:
before[0][0] = after[0][0]
elif i == 0:
before[i][j] = after[i][j] - after[i][j - 1]
elif j == 0:
before[i][j] = after[i][j] - after[i - 1][j]
else:
before[i][j] = after[i][j] + after[i - 1][j - 1] \
- after[i - 1][j] - after[i][j - 1]
# Return the before[][] matrix
return before
if __name__ == "__main__":
after = [[1, 3, 6], [3, 7, 11]]
ans = computeBeforeMatrix(after)
for row in ans:
print(" ".join(map(str, row)))
C#
// C# code to Compute before Matrix
using System;
using System.Collections.Generic;
class GfG {
// Function to compute before matrix
static List<List<int>> computeBeforeMatrix(List<List<int>> after) {
int n = after.Count, m = after[0].Count;
// Declaring a 2D list to store
// the values of the before Matrix
List<List<int>> before = new List<List<int>>();
for (int i = 0; i < n; i++)
before.Add(new List<int>(new int[m]));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i == 0 && j == 0)
before[0][0] = after[0][0];
else if (i == 0)
before[i][j] = after[i][j] - after[i][j - 1];
else if (j == 0)
before[i][j] = after[i][j] - after[i - 1][j];
else
before[i][j] = after[i][j] + after[i - 1][j - 1]
- after[i - 1][j] - after[i][j - 1];
}
}
// Return the before[][] matrix
return before;
}
static void Main() {
List<List<int>> after = new List<List<int>> {
new List<int> { 1, 3, 6 },
new List<int> { 3, 7, 11 }
};
List<List<int>> ans = computeBeforeMatrix(after);
foreach (List<int> row in ans) {
Console.WriteLine(string.Join(" ", row));
}
}
}
JavaScript
// JavaScript code to Compute before Matrix
// Function to compute before matrix
function computeBeforeMatrix(after) {
let n = after.length, m = after[0].length;
// Declaring a 2D array to store
// the values of the before Matrix
let before = Array.from({ length: n }, () => Array(m).fill(0));
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if (i === 0 && j === 0)
before[0][0] = after[0][0];
else if (i === 0)
before[i][j] = after[i][j] - after[i][j - 1];
else if (j === 0)
before[i][j] = after[i][j] - after[i - 1][j];
else
before[i][j] = after[i][j] + after[i - 1][j - 1]
- after[i - 1][j] - after[i][j - 1];
}
}
// Return the before[][] matrix
return before;
}
let after = [[1, 3, 6], [3, 7, 11]];
let ans = computeBeforeMatrix(after);
ans.forEach(row => console.log(row.join(" ")));
Time Complexity: O(n * m) where n is the number of rows and m is the number of columns
Auxiliary Space: O(n * m)
Similar Reads
Minimum Steps to obtain N from 1 by the given operations Given an integer N, the task is to find the minimum number of operations needed to obtain the number N starting from 1. Below are the operations: Add 1 to the current number.Multiply the current number by 2.Multiply the current number by 3. Print the minimum number of operations required and the cor
15+ min read
Basic Operators in Java Java provides a rich operator environment. We can classify the basic operators in java in the following groups: Arithmetic OperatorsRelational OperatorsBitwise OperatorsAssignment OperatorsLogical Operators Let us now learn about each of these operators in detail. 1. Arithmetic Operators: Arithmetic
10 min read
Minimum operations required to convert A into B using given conditions Given two integers A and B, you have to choose two integers X and Y such that X must be odd, and Y must be even. Then you have to make A equal to B by using one out of two operations below at a time (possible zero time), the task is to find the minimum number of operations required to make integer A
5 min read
Implement *, - and / operations using only + arithmetic operator Given two numbers, perform multiplication, subtraction, and division operations on them, using '+' arithmetic operator only. Operations can be performed as follows: Subtraction :- a - b = a + (-1)*b. Multiplication :- a * b = a + a + a ... b times. Division :- a / b = continuously subtract b from a
12 min read
Reduce N to 0 or less by given X and Y operations Given three integers N, X, and Y, the task is to check if it is possible to reduce N to 0 or less by the following operations: Update N to ?N/2? + 10, at most X timesUpdate N to N - 10, at most Y times. Example: Input: N = 100, X = 3, Y = 4Output: YesExplanation:Update N = 100 to ?100/2? + 10 = 60.U
6 min read