Find all permuted rows of a given row in a matrix

We are given a 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.


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.

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

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

// C++ program to find all permutations of a given row
#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++)
    // 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)
        // 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())
        if (j != n)
        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;


0, 2

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

Exercise : 
Extend the above solution to work for input matrix where all elements of a row don’t have be distinct. (Hint : We can use Hash Map instead of Hash Set)

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at #techcodebit #google #microsoft #facebook #interview portal #jobplacements


Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar