How to check if a matrix rows contain numbers without repetition in Java

1 Answer

0 votes
import java.util.HashSet; 

public class MatrixRowCheck {
    public static boolean areRowsUnique(int[][] matrix) {
        for (int[] row : matrix) {
            // Use a HashSet to track numbers in the current row
            HashSet<Integer> seenNumbers = new HashSet<>();
            for (int num : row) {
                // If the number is already in the set, it's a repetition
                if (!seenNumbers.add(num)) {
                    return false; // Row contains duplicates
                }
            }
        }
        return true; // All rows are unique
    }

    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 7}
        };

        System.out.println("Rows contain unique numbers: " + areRowsUnique(matrix));
    }
}

   
   
/*
run:
   
Rows contain unique numbers: false
   
*/

 



answered May 23, 2025 by avibootz
...