The Wayback Machine - https://web.archive.org/web/20220105222709/https://www.geeksforgeeks.org/replace-diagonal-elements-in-each-row-of-given-matrix-by-kth-smallest-element-of-that-row/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Replace diagonal elements in each row of given Matrix by Kth smallest element of that row

  • Last Updated : 05 Jan, 2022

Given a matrix mat[ ][ ] of size N*N and an integer K, containing integer values, the task is to replace diagonal elements by the Kth smallest element of row.

Examples: 

Resolution Days 2022 GeeksforGeeks

Input: mat[][]= {{1, 2, 3, 4}
                         {4, 2, 7, 6}
                         {3, 5, 1, 9}
                         {2, 4, 6, 8}}
K = 2
Output: 2, 2, 3, 4
             4, 4, 7, 6
             3, 5, 3, 8
             2, 4, 6, 4
Explanation: 2nd smallest element of 1st row = 2
2nd smallest element of 2nd row is 4
2nd smallest element of 3rd row is 3
2nd smallest element of 4th row is 4             

Input: mat[][] = {{1, 2, 3}
                          {7, 9, 8}
                          {2, 3, 6}}
K = 2
Output: 2, 2, 3
             7, 8, 8
             2, 3, 3



 

Approach: The solution is based on the concept of sorting. Follow the steps mentioned below:

  • Traverse the matrix row-wise.
  • Copy this row in another list.
  • Sort the list and get the Kth smallest element and replace the diagonal element with that.

Below is the implementation of the above approach.

C++




// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
  
const int N = 4;
  
// Function to print Matrix
void showMatrix(int mat[][N])
{
    int i, j;
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
            cout << mat[i][j] << " ";
        }
        cout << endl;
    }
}
  
// Function to return k'th smallest element
// in a given array
int kthSmallest(int arr[], int n, int K)
{
    // Sort the given array
    sort(arr, arr + n);
  
    // Return k'th element
    // in the sorted array
    return arr[K - 1];
}
  
// Function to replace diagonal elements
// with Kth min element of row.
void ReplaceDiagonal(int mat[][N], int K)
{
    int i, j;
    int arr[N];
  
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++)
            arr[j] = mat[i][j];
        mat[i][i] = kthSmallest(arr, N, K);
    }
    showMatrix(mat);
}
  
// Utility Main function.
int main()
{
    int mat[][N] = { { 1, 2, 3, 4 },
                     { 4, 2, 7, 6 },
                     { 3, 5, 1, 9 },
                     { 2, 4, 6, 8 } };
  
    int K = 3;
    ReplaceDiagonal(mat, K);
    return 0;
}
Output
3 2 3 4 
4 6 7 6 
3 5 5 9 
2 4 6 6 

Time Complexity: O(N2 * logN)
Auxiliary Space: O(N)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!