![]() |
VOOZH | about |
Given a matrix of n rows and m columns. The task is to replace each matrix element with Greatest Common Divisor of its row or column, whichever is maximum. That is, for each element (i, j) replace it from GCD of i'th row or GCD of j'th row, whichever is greater.
Examples :
Input : mat[3][4] = {1, 2, 3, 3,
4, 5, 6, 6
7, 8, 9, 9}
Output : 1 1 3 3
1 1 3 3
1 1 3 3
For index (0,2), GCD of row 0 is 1, GCD of row 2 is 3.
So replace index (0,2) with 3 (3>1).
The idea is to us concept discussed here LCM of an array to find the GCD of row and column.
Using the brute force, we can traverse element of matrix, find the GCD of row and column corresponding to the element and replace it with maximum of both.
An Efficient method is to make two arrays of size n and m for row and column respectively. And store the GCD of each row and each column. An Array of size n will contain GCD of each row and array of size m will contain the GCD of each column. And replace each element with maximum of its corresponding row GCD or column GCD.
Below is the implementation of this approach:
1 1 3 3 1 1 3 3 1 1 3 3
Time Complexity : O(mn).
Auxiliary Space : O(m + n). Since m + n extra space has been taken.