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
Matrix Row and Column ValidationInput Matrix 3×3123231312Row ValidationRow 1: {1,2,3} ✓Row 2: {2,3,1} ✓Row 3: {3,1,2} ✓Column ValidationCol 1: {1,2,3} ✓Col 2: {2,3,1} ✓Col 3: {3,1,2} ✓Required Set{1, 2, 3}Every row and columnmust contain this setRESULT: trueAll validations passedAlgorithm: Check each row and column contains exactly numbers 1 to n
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
Asked in
Amazon 15 Google 12 Microsoft 8 Apple 6
25.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen