Java - Find Duplicate Rows in a Binary Matrix
import java.util.HashSet;
import java.util.Set;
public class DuplicateRowsInBinaryMatrix {
// Function to find duplicate rows in the matrix
public static void findDuplicateRows(int[][] matrix) {
Set<String> uniqueRows = new HashSet<>(); // To store unique rows
Set<String> duplicateRows = new HashSet<>(); // To store duplicate rows
// Iterate through each row
for (int i = 0; i < matrix.length; i++) {
StringBuilder rowString = new StringBuilder();
// Convert the row into a string for easy comparison
for (int j = 0; j < matrix[i].length; j++) {
rowString.append(matrix[i][j]);
}
// If rowString is already present in uniqueRows, it's a duplicate
if (uniqueRows.contains(rowString.toString())) {
duplicateRows.add(rowString.toString());
} else {
uniqueRows.add(rowString.toString());
}
}
// Print the duplicate rows
if (duplicateRows.isEmpty()) {
System.out.println("No duplicate rows found.");
} else {
System.out.println("Duplicate rows:");
for (String row : duplicateRows) {
System.out.println(row);
}
}
}
public static void main(String[] args) {
// Example binary matrix
int[][] matrix = {
{1, 0, 1},
{0, 1, 0},
{1, 0, 1},
{1, 1, 0}
};
findDuplicateRows(matrix);
}
}
Explanation:
HashSet<String>:
uniqueRows: Stores the rows that have been seen already.
duplicateRows: Stores the rows that are duplicates.
Row Conversion to String: Each row is converted to a string by appending the elements. This allows us to use the string representation for comparison between rows.
Identifying Duplicates:
If the row string is already present in the uniqueRows set, it’s a duplicate, and we add it to the duplicateRows set.
Otherwise, the row is added to the uniqueRows set.
Output: At the end, we print out all duplicate rows.
Example Output:
For the input matrix:
1 0 1
0 1 0
1 0 1
1 1 0
The output will be:
Duplicate rows:
101