You are given an n x n
integer matrix matrix
. The matrix contains all the integers from 1
to n
. Your task is to check if every row and every column contains all the integers from 1
to n
.
Return true
if every row and every column of the matrix contains all the integers from 1
to n
, otherwise return false
.
n
?
n
can vary, but let’s assume it fits within reasonable memory constraints, so 1 <= n <= 100
.n x n
.Validation of Individual Rows and Columns:
To ensure each row and column contains all numbers from 1
to n
, we can use sets for comparison since set operations (like union and difference) are efficient.
Steps:
1
to n
.false
.true
.def checkValid(matrix):
n = len(matrix)
reference_set = set(range(1, n + 1))
# Check all rows
for row in matrix:
if set(row) != reference_set:
return False
# Check all columns
for col in range(n):
column_set = set(matrix[row][col] for row in range(n))
if column_set != reference_set:
return False
return True
O(n^2)
n x n
matrix twice (once for rows and once for columns).O(n)
for each row and column, summing to O(n^2)
.O(n)
n
.reference_set
consisting of numbers from 1
to n
.reference_set
. If any row does not match, we return false
.reference_set
. If any column does not match, return false
.true
.This ensures that every row and column contains all the integers from 1
to n
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?