2133. Check if Every Row and Column Contains All Numbers

use set to check row, then col

class Solution {
    public boolean checkValid(int[][] matrix) {
        int n = matrix.length;

        Set<Integer> set = new HashSet<>();
        for (int i = 0 ; i < n; i++) {
            for (int j = 0 ; j < n; j++) {
                // if there is a number existed, it's wrong!
                if (set.contains(matrix[i][j])) {
                    return false;
                }
                set.add(matrix[i][j]);
            }
            set = new HashSet<>();
        }
        
        set = new HashSet<>();
        for (int j = 0 ; j < n; j++) {
            for (int i = 0 ; i < n; i++) {
                // if there is a number existed, it's wrong!
                if (set.contains(matrix[i][j])) {
                    return false;
                }
                set.add(matrix[i][j]);
            }
            set = new HashSet<>();
        }
        return true;
    }
}

use Xor

T: O(n^2)

S: O(1)

Last updated

Was this helpful?