2133. Check if Every Row and Column Contains All Numbers
Description
An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive).
Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.
Example 1:
Input: matrix = [[1,2,3],[3,1,2],[2,3,1]] Output: true Explanation: In this case, n = 3, and every row and column contains the numbers 1, 2, and 3. Hence, we return true.
Example 2:
Input: matrix = [[1,1,1],[1,2,3],[1,2,3]] Output: false Explanation: In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3. Hence, we return false.
Constraints:
n == matrix.length == matrix[i].length1 <= n <= 1001 <= matrix[i][j] <= n
Solutions
Solution 1: Hash Table
Thinking
Every row and column must contain \(1\ldots n\) exactly once. With \(n\le 100\), checking that each line’s set has size \(n\) is enough.
Rows are the matrix itself; columns come from the transpose. A set of size \(n\) means no duplicates, hence a permutation of \(1\ldots n\) given the value range.
Validate every sequence in \(\texttt{chain}(\textit{matrix},\texttt{zip}(*\textit{matrix}))\).
Traverse each row and column of the matrix, using a hash table to record whether each number has appeared. If any number appears more than once in a row or column, return false; otherwise, return true
The time complexity is \(O(n^2)\), and the space complexity is \(O(n)\). Here, \(n\) is the size of the matrix.
1 2 3 4 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |

