Skip to content

2133. Check if Every Row and Column Contains All Numbers 👍

  • Time: $O(n^2)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  bool checkValid(vector<vector<int>>& matrix) {
    const int n = matrix.size();

    for (int i = 0; i < n; ++i) {
      bitset<101> row;
      bitset<101> col;
      for (int j = 0; j < n; ++j) {
        row[matrix[i][j]] = true;
        col[matrix[j][i]] = true;
      }
      if (min(row.contains(), col.contains()) < n)
        return false;
    }

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public boolean checkValid(int[][] matrix) {
    final int n = matrix.length;

    for (int i = 0; i < n; ++i) {
      Set<Integer> row = new HashSet<>();
      Set<Integer> col = new HashSet<>();
      for (int j = 0; j < n; ++j) {
        row.add(matrix[i][j]);
        col.add(matrix[j][i]);
      }
      if (Math.min(row.size(), col.size()) < n)
        return false;
    }

    return true;
  }
}
1
2
3
4
class Solution:
  def checkValid(self, matrix: list[list[int]]) -> bool:
    return all(min(len(set(row)), len(set(col))) == len(matrix)
               for row, col in zip(matrix, zip(*matrix)))