Problem Description
An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given such a matrix, determine if it is valid. Return true if every row and every column contains all numbers from 1 to n; otherwise, return false.
Key Insights
- Each row must contain all numbers from 1 to n with no duplicates.
- Each column must also contain all numbers from 1 to n.
- Use a set to compare the elements in each row and column with the expected set {1, 2, ..., n}.
- Iterate through the matrix first by rows and then by columns to perform the necessary checks.
Space and Time Complexity
Time Complexity: O(n²) - Each element of the matrix is examined once. Space Complexity: O(n) - A set of size n is used for verification during row and column checks.
Solution
The solution involves:
- Creating an expected set containing numbers from 1 to n.
- Iterating through each row, converting it into a set, and comparing it with the expected set.
- Iterating through each column, collecting the elements into a set, and comparing it with the expected set. If any row or column fails the check, the function immediately returns false. If all checks pass, the function returns true. This approach efficiently verifies that both rows and columns meet the problem requirements.