Skip to content
Related Articles

Related Articles

Improve Article

Find all permuted rows of a given row in a matrix

  • Difficulty Level : Easy
  • Last Updated : 25 May, 2021

We are given an m*n matrix of positive integers and a row number. The task is to find all rows in given matrix which are permutations of given row elements. It is also given that values in every row are distinct.

Examples:  

Input : mat[][] = {{3, 1, 4, 2}, 
                   {1, 6, 9, 3},
                   {1, 2, 3, 4},
                   {4, 3, 2, 1}}
        row = 3    
Output: 0, 2
Rows at indexes 0 and 2 are permutations of
row at index 3. 

A simple solution is to one by one sort all rows and check all rows. If any row is completely equal to the given row, that means the current row is a permutation of the given row. The time complexity for this approach will be O(m*n log n).

An efficient approach is to use hashing. Simply create a hash set for the given row. After hash set creation, traverse through the remaining rows, and for every row check if all of its elements are present in the hash set or not.  

CPP




// C++ program to find all permutations of a given row
#include<bits/stdc++.h>
#define MAX 100
 
using namespace std;
 
// Function to find all permuted rows of a given row r
void permutatedRows(int mat[][MAX], int m, int n, int r)
{
    // Creating an empty set
    unordered_set<int> s;
 
    // Count frequencies of elements in given row r
    for (int j=0; j<n; j++)
        s.insert(mat[r][j]);
 
    // Traverse through all remaining rows
    for (int i=0; i<m; i++)
    {
        // we do not need to check for given row r
        if (i==r)
            continue;
 
        // initialize hash i.e; count frequencies
        // of elements in row i
        int j;
        for (j=0; j<n; j++)
            if (s.find(mat[i][j]) == s.end())
                break;
        if (j != n)
           continue;
 
        cout << i << ", ";
    }
}
 
// Driver program to run the case
int main()
{
    int m = 4, n = 4,r = 3;
    int mat[][MAX] = {{3, 1, 4, 2},
                      {1, 6, 9, 3},
                      {1, 2, 3, 4},
                      {4, 3, 2, 1}};
    permutatedRows(mat, m, n, r);
    return 0;
}

Java




// Java program to find all permutations of a given row
import java.util.*;
 
class GFG
{
     
static int MAX = 100;
 
// Function to find all permuted rows of a given row r
static void permutatedRows(int mat[][], int m, int n, int r)
{
    // Creating an empty set
    LinkedHashSet<Integer> s = new LinkedHashSet<>();
 
 
    // Count frequencies of elements in given row r
    for (int j = 0; j < n; j++)
        s.add(mat[r][j]);
 
    // Traverse through all remaining rows
    for (int i = 0; i < m; i++)
    {
        // we do not need to check for given row r
        if (i == r)
            continue;
 
        // initialize hash i.e; count frequencies
        // of elements in row i
        int j;
        for (j = 0; j < n; j++)
            if (!s.contains(mat[i][j]))
                break;
        if (j != n)
        continue;
 
        System.out.print(i+", ");
    }
}
 
// Driver program to run the case
public static void main(String[] args)
{
    int m = 4, n = 4,r = 3;
    int mat[][] = {{3, 1, 4, 2},
                    {1, 6, 9, 3},
                    {1, 2, 3, 4},
                    {4, 3, 2, 1}};
    permutatedRows(mat, m, n, r);
}
}
 
// This code has been contributed by 29AjayKumar

Python3




# Python program to find all
# permutations of a given row
 
# Function to find all
# permuted rows of a given row r
def permutatedRows(mat, m, n, r):
 
 
    # Creating an empty set
    s=set()
 
    # Count frequencies of
    # elements in given row r
    for j in range(n):
        s.add(mat[r][j])   
 
    # Traverse through all remaining rows
    for i in range(m):
 
        # we do not need to check
        # for given row r
        if i == r:
            continue
 
        # initialize hash i.e
        # count frequencies
        # of elements in row i
        for j in range(n):
            if mat[i][j] not in s:
 
                # to avoid the case when last
                # element does not match
                j = j - 2
                break;
        if j + 1 != n:
            continue
        print(i)
             
     
 
# Driver program to run the case
m = 4
n = 4
r = 3
mat = [[3, 1, 4, 2],
       [1, 6, 9, 3],
       [1, 2, 3, 4],
       [4, 3, 2, 1]]
 
permutatedRows(mat, m, n, r)
 
# This code is contributed
# by Upendra Singh Bartwal.

C#




// C# program to find all permutations of a given row
using System;
using System.Collections.Generic;
 
class GFG
{
     
static int MAX = 100;
 
// Function to find all permuted rows of a given row r
static void permutatedRows(int [,]mat, int m, int n, int r)
{
    // Creating an empty set
    HashSet<int> s = new HashSet<int>();
 
 
    // Count frequencies of elements in given row r
    for (int j = 0; j < n; j++)
        s.Add(mat[r, j]);
 
    // Traverse through all remaining rows
    for (int i = 0; i < m; i++)
    {
        // we do not need to check for given row r
        if (i == r)
            continue;
 
        // initialize hash i.e; count frequencies
        // of elements in row i
        int j;
        for (j = 0; j < n; j++)
            if (!s.Contains(mat[i,j]))
                break;
        if (j != n)
        continue;
 
        Console.Write(i+", ");
    }
}
 
// Driver program to run the case
public static void Main(String[] args)
{
    int m = 4, n = 4,r = 3;
    int [,]mat = {{3, 1, 4, 2},
                    {1, 6, 9, 3},
                    {1, 2, 3, 4},
                    {4, 3, 2, 1}};
    permutatedRows(mat, m, n, r);
}
}
 
/* This code contributed by PrinciRaj1992 */

Javascript




<script>
 
// Javascript program to find all permutations of a given row
 
let MAX = 100;
   
// Function to find all permuted rows of a given row r
function permutatedRows(mat, m, n, r)
{
    // Creating an empty set
    let s = new Set();
   
   
    // Count frequencies of elements in given row r
    for (let j = 0; j < n; j++)
        s.add(mat[r][j]);
   
    // Traverse through all remaining rows
    for (let i = 0; i < m; i++)
    {
        // we do not need to check for given row r
        if (i == r)
            continue;
   
        // initialize hash i.e; count frequencies
        // of elements in row i
        let j;
        for (j = 0; j < n; j++)
            if (!s.has(mat[i][j]))
                break;
        if (j != n)
        continue;
   
        document.write(i+", ");
    }
}
 
 
// Driver program
 
    let m = 4, n = 4,r = 3;
    let mat = [[ 3, 1, 4, 2],
               [1, 6, 9, 3],
               [1, 2, 3, 4],
               [4, 3, 2, 1]];
    permutatedRows(mat, m, n, r);
 
 
</script>

Output:  



0, 2

Time complexity: O(m*n) 
Auxiliary space: O(n)

Another approach to the solution is using the Standard Template Library(STL):  

CPP




// C++ program to find all permutations of a given row
#include<bits/stdc++.h>
#define MAX 100
 
using namespace std;
 
// Function to find all permuted rows of a given row r
void permutatedRows(int mat[][MAX], int m, int n, int r)
{
   for (int i=0; i<m&&i!=r; i++){
        if(is_permutation(mat[i],mat[i]+n,mat[r])) cout<<i<<",";
    }
}
 
// Driver program to run the case
int main()
{
    int m = 4, n = 4,r = 3;
    int mat[][MAX] = {{3, 1, 4, 2},
                      {1, 6, 9, 3},
                      {1, 2, 3, 4},
                      {4, 3, 2, 1}};
    permutatedRows(mat, m, n, r);
    return 0;
}

Output: 

0, 2

Exercise : 
Extend the above solution to work for an input matrix where all elements of a row don’t have to be distinct. (Hit: We can use Hash Map instead of a Hash Set)
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :