VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-permuted-rows-given-row-matrix/

⇱ Find all Permuted Rows of a Given Row in a Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find all Permuted Rows of a Given Row in a Matrix

Last Updated : 27 Feb, 2026

Given a matrix mat[][] of size m × n and a positive integer ind (0 ≤ ind < m), determine all row indices i such that the elements of row i form a permutation of the elements in row ind.
It is guaranteed that every row contains distinct elements.

Note: Two rows are considered permutations of each other if they contain the same elements in any order.

Examples: 

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

Input : ind = 0, mat[][] = [[1, 2],
[2, 1]]
Output: 1
Explanation: Row at indexes 1 is permutation of row at index 0.

[Naive Approach] - Using Sorting - O(m × n × log n) Time and O(1) Space

The idea is to sort all the rows of matrix mat[][] and check all the rows. If any row is completely equal to the row at index ind, it means the row is a permutation of the given row.


Output
0 2 

[Expected Approach] - Using HashSet - O(m × n) Time and O(n) Space

The idea is to create a HashSet for the row with index ind in the matrix mat[][], then traverse through all the rows and check if all of its elements are present in the HashSet or not.  


Output
0 2 

Note : In C++, this problem can be efficiently solved using the is_permutation function from the <algorithm> library. It checks whether two ranges contain the same elements in any order. Using this, we can compare the row at index ind with each row of the matrix to find all permuted rows.

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

Comment
Article Tags:
Article Tags: