Open In App

Compute Matrix before Given Operations

Last Updated : 18 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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[][] matrix

See 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(" ")));

Output
1 2 3 
2 2 1 

Time Complexity: O(n * m) where n is the number of rows and m is the number of columns
Auxiliary Space: O(n * m)


Next Article

Similar Reads