The Wayback Machine - https://web.archive.org/web/20220106163230/https://www.geeksforgeeks.org/replace-each-matrix-element-with-its-row-product-except-that-element/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Replace each Matrix element with its row product except that element

  • Last Updated : 05 Jan, 2022

Given a 2D-array mat[][] of order M*N. The task is to replace every element of each row with the product of other elements of the same row.

Examples: 

Resolution Days 2022 GeeksforGeeks

Input: mat[][] = {{3, 4, 1}, {6, 1, 7}, {2, 9, 8}}
Output:
4, 3, 12
7, 42, 6
72, 16, 18             

Input: mat[][] = {{13, 4, 5}, {6, 11, 1}}
Output:
20, 65, 52
11, 6, 66



Approach: The idea is straightforward. Traverse the matrix row-wise and find the product of each row. In the second traversal find the replacement value for each cell of the row. Follow the steps below to solve the problem:

  • Initialize the variables mul, i and j.
  • Iterate over the range [0, M) using the variable i and perform the following tasks:
    • Set the value of mul as 1.
    • Iterate over the range [0, N) using the variable j and perform the following tasks:
      • Set the value of mul as mul*mat[i][j].
    • Iterate over the range [0, N) using the variable j and perform the following tasks:
      • Set the value of mat[i][j] as mul/mat[i][j].
  • After performing the above steps, print the values of mat[][] as the answer.

Below is the implementation of the above approach.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
const int M = 3, N = 3;
  
// Show Matrix.
void showMatrix(vector<vector<int> >& mat)
{
    int i, j;
    for (i = 0; i < M; i++) {
        for (j = 0; j < N; j++) {
            cout << mat[i][j] << " ";
        }
        cout << endl;
    }
}
  
// Utility Function
void ReplaceWithProduct(vector<vector<int> >& mat)
{
    int mul, i, j;
    for (i = 0; i < M; i++) {
        mul = 1;
        for (j = 0; j < N; j++)
            mul *= mat[i][j];
        for (j = 0; j < N; j++)
            mat[i][j] = mul / mat[i][j];
    }
    showMatrix(mat);
}
  
// Utility Main function.
int main()
{
    vector<vector<int> > mat = { { 3, 6, 2 },
                                 { 1, 4, 9 },
                                 { 5, 3, 8 } };
    ReplaceWithProduct(mat);
    return 0;
}
Output:
12 6 18 
36 9 4 
24 40 15

Time Complexity: O(N*N)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!