Check if Every Row and Column Contains All Numbers - Problem
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.
Input & Output
Example 1 — Valid Matrix
$
Input:
matrix = [[1,2,3],[2,3,1],[3,1,2]]
›
Output:
true
💡 Note:
Each row contains [1,2,3] and each column contains [1,2,3] in some order. Row 1: [1,2,3]✓, Row 2: [2,3,1]✓, Row 3: [3,1,2]✓. Column 1: [1,2,3]✓, Column 2: [2,3,1]✓, Column 3: [3,1,2]✓
Example 2 — Invalid Matrix
$
Input:
matrix = [[1,1,1],[1,2,3],[1,2,3]]
›
Output:
false
💡 Note:
Row 1 contains [1,1,1] which is missing 2 and 3, and has duplicate 1s. This violates the requirement that each row must contain all numbers from 1 to n exactly once.
Example 3 — 2x2 Valid Matrix
$
Input:
matrix = [[1,2],[2,1]]
›
Output:
true
💡 Note:
For n=2, each row and column must contain [1,2]. Row 1: [1,2]✓, Row 2: [2,1]✓, Column 1: [1,2]✓, Column 2: [2,1]✓
Constraints
- n == matrix.length == matrix[i].length
- 1 ≤ n ≤ 100
- 1 ≤ matrix[i][j] ≤ n
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
3x3 matrix where each cell contains numbers 1-3
2
Validate Rows
Check each row contains exactly {1,2,3}
3
Validate Columns
Check each column contains exactly {1,2,3}
4
Result
Return true if all pass, false otherwise
Key Takeaway
🎯 Key Insight: Each row and column must be a perfect permutation of numbers 1 to n
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code