Find duplicate rows present in a given binary matrix by traversing the matrix only once.

For example,

Input:
 
[1  0  0  1  0]
[0  1  1  0  0]
[1  0  0  1  0]
[0  0  1  1  0]
[0  1  1  0  0]
 
Output: {3, 5}
 
Explanation: Row #3 is duplicate of row #1 and row #5 is duplicate of row #2

Practice this problem

Approach 1 (Using Trie)

The idea is to insert each row of the given binary matrix into a binary Trie. The alphabet size of a binary trie is only limited to Boolean numbers (0 and 1). If a row is seen before (i.e., it is already present in the Trie), report it as duplicate.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
Duplicate row found: Row #3
Duplicate row found: Row #5

The time complexity of the above solution is O(N.M) and requires O(N.M) extra space for Trie data structure, where M and N are dimensions of the matrix.

Approach 2 (Converting to Decimal)

The idea is to convert each row to its decimal equivalent and check if the decimal value is seen before or not. If it is seen before, report the row as duplicate. This method will only work for N < 32 (or N < 64 if long datatype is used), where N is the total number of columns in the matrix.

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
Duplicate row found: Row #3
Duplicate row found: Row #5

The time complexity of the above solution is O(N.M) and requires O(M) extra space for the hashset, where M and N are dimensions of the matrix.