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

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:Â
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 Matrixvoid 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 arrayint 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;} |
Java
// Java code to find the maximum median// of a sub array having length at least K.import java.util.*;public class GFG{Â
  static int N = 4;Â
  // Function to print Matrix  static void showMatrix(int mat[][])  {    int i, j;    for (i = 0; i < N; i++) {      for (j = 0; j < N; j++) {        System.out.print(mat[i][j] + " ");      }      System.out.println();    }  }Â
  // Function to return k'th smallest element  // in a given array  static int kthSmallest(int arr[], int n, int K)  {    // Sort the given array    Arrays.sort(arr);Â
    // Return k'th element    // in the sorted array    return arr[K - 1];  }Â
  // Function to replace diagonal elements  // with Kth min element of row.  static void ReplaceDiagonal(int mat[][], int K)  {    int i, j;    int arr[] = new int[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);  }Â
  // Driver code  public static void main(String args[])  {    int mat[][] = { { 1, 2, 3, 4 },                   { 4, 2, 7, 6 },                   { 3, 5, 1, 9 },                   { 2, 4, 6, 8 } };Â
    int K = 3;    ReplaceDiagonal(mat, K);  }}Â
// This code is contributed by Samim Hossain Mondal. |
Python3
# Python code for the above approachN = 4Â
# Function to print Matrixdef showMatrix(mat):    i = None    j = None    for i in range(N):        for j in range(N):            print(mat[i][j], end= " ")        print('')     # Function to return k'th smallest element# in a given arraydef kthSmallest(arr, n, K):Â
    # Sort the given array    arr.sort()Â
    # Return k'th element    # in the sorted array    return arr[K - 1]Â
# Function to replace diagonal elements# with Kth min element of row.def ReplaceDiagonal(mat, K):    i = None    j = None    arr = [0] * NÂ
    for i in range(N):        for j in range(N):            arr[j] = mat[i][j]        mat[i][i] = kthSmallest(arr, N, K)    showMatrix(mat)Â
# Utility Main function.mat = [[1, 2, 3, 4], [4, 2, 7, 6], [3, 5, 1, 9], [2, 4, 6, 8]]Â
K = 3ReplaceDiagonal(mat, K)Â
# This code is contributed by Saurabh Jaiswal |
C#
// C# code to find the maximum median// of a sub array having length at least K.using System;Â
public class GFG {Â
  static int N = 4;Â
  // Function to print Matrix  static void showMatrix(int[, ] mat)  {    int i, j;    for (i = 0; i < N; i++) {      for (j = 0; j < N; j++) {        Console.Write(mat[i, j] + " ");      }      Console.WriteLine();    }  }Â
  // Function to return k'th smallest element  // in a given array  static int kthSmallest(int[] arr, int n, int K)  {    // Sort the given array    Array.Sort(arr);Â
    // Return k'th element    // in the sorted array    return arr[K - 1];  }Â
  // Function to replace diagonal elements  // with Kth min element of row.  static void ReplaceDiagonal(int[, ] mat, int K)  {    int i, j;    int[] arr = new int[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);  }Â
  // Driver code  public static void Main()  {    int[, ] mat = { { 1, 2, 3, 4 },                   { 4, 2, 7, 6 },                   { 3, 5, 1, 9 },                   { 2, 4, 6, 8 } };Â
    int K = 3;    ReplaceDiagonal(mat, K);  }}Â
// This code is contributed by ukasp. |
Javascript
<script>       // JavaScript code for the above approach        let N = 4;Â
       // Function to print Matrix       function showMatrix(mat) {           let i, j;           for (i = 0; i < N; i++) {               for (j = 0; j < N; j++) {                   document.write(mat[i][j] + " ");               }               document.write('<br>')           }       }Â
       // Function to return k'th smallest element       // in a given array       function kthSmallest(arr, n, K)       {                   // Sort the given array           arr.sort(function (a, b) { return a - b })Â
           // Return k'th element           // in the sorted array           return arr[K - 1];       }Â
       // Function to replace diagonal elements       // with Kth min element of row.       function ReplaceDiagonal(mat, K)        {           let i, j;           let arr = new Array(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.       let mat = [[1, 2, 3, 4],       [4, 2, 7, 6],       [3, 5, 1, 9],       [2, 4, 6, 8]];Â
       let K = 3;       ReplaceDiagonal(mat, K);Â
 // This code is contributed by Potta Lokesh   </script> |
Â
Â
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)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



