Check if Every Row and Column Contains All Numbers - Problem
Think of this as a magic square validation problem! You're given an n × n matrix and need to determine if it's a valid complete matrix.
A matrix is considered valid if:
- Every row contains all integers from
1ton(inclusive) - Every column contains all integers from
1ton(inclusive)
For example, in a 3×3 matrix, each row and column must contain exactly the numbers [1, 2, 3] in any order.
Goal: Return true if the matrix is valid, false otherwise.
Input & Output
example_1.py — Valid 3×3 Matrix
$
Input:
matrix = [[1,2,3],[3,1,2],[2,3,1]]
›
Output:
true
💡 Note:
Each row contains [1,2,3] in some order, and each column also contains [1,2,3] in some order. Row 0: {1,2,3}, Row 1: {3,1,2}, Row 2: {2,3,1}. Column 0: {1,3,2}, Column 1: {2,1,3}, Column 2: {3,2,1}.
example_2.py — Invalid Matrix (Missing Numbers)
$
Input:
matrix = [[1,1,1],[1,2,3],[1,2,3]]
›
Output:
false
💡 Note:
The first row contains [1,1,1] which has duplicates and is missing 2 and 3. Even though other rows might be valid, all rows must contain exactly the numbers 1 to n.
example_3.py — Single Element Matrix
$
Input:
matrix = [[1]]
›
Output:
true
💡 Note:
A 1×1 matrix with the single element 1 is valid since both the row and column contain exactly the numbers from 1 to 1.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Tracking
Create empty sets to track numbers seen in each row and column
2
Single Pass Collection
Traverse matrix once, adding each element to its row and column sets
3
Validation Check
Verify each row and column set contains exactly numbers 1 to n
Key Takeaway
🎯 Key Insight: We can validate both row and column constraints simultaneously during a single traversal, making the solution both time and space efficient while maintaining clarity.
Time & Space Complexity
Time Complexity
O(n²)
Single pass through n×n matrix, O(1) set operations for each element
⚠ Quadratic Growth
Space Complexity
O(n²)
O(n) space for each of the n rows and n columns sets
⚠ Quadratic Space
Constraints
- n == matrix.length == matrix[i].length
- 1 ≤ n ≤ 100
- 1 ≤ matrix[i][j] ≤ n
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code