Last Updated: 25 Nov, 2020

Ninja and Crazy sum

Easy
Asked in company
Codenation

Problem statement

Ninja is learning summation and is interested in performing summation on a matrix. Standing at a particular row and column, he is interested in adding all the column values to the right of it and belonging to the same row and not including the present column value. He performs such operations at every row and column of the matrix. Can you return the final matrix that Ninja gets?

Input Format:
The first line contains ‘T’, denoting the number of test cases.

The first line of each test case contains two space-separated integers, ‘N’ and ‘M’, denoting the number of rows and the number of columns respectively.

 Each of the next ‘N’ lines of the test case contains ‘M’ space-separated integers denoting ‘M’ integers of every row respectively. 
Output Format:
For each test case, print the resultant matrix.
Note:
You are not required to print the expected output or take the matrix input; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 10
1 <= N <= 10^3
1 <= M <= 10^3
-10^5 <= input[i][j] <= 10^5

Time Limit: 1 sec

Approaches

01 Approach

The key here is to traverse all the lines sequentially, and for each line, we calculate the required sum at the given index.

 

The steps are as follows:

  • We initialize a variable ‘sum’ to 0, which will be storing the value of the sum from the right.
  • We will iterate over all the rows, i.e., i = 0 to i = N - 1:
    • We will iterate over all the columns in backward order, i.e., j = M-1 to 0:
      • We store the value of matrix[i][j] in a variable ‘temp’.
      • We replace the value of matrix[i][j] with sum.
      • We increment the value of the sum by matrix[i][j].
  • We will return the matrix as the final answer.