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
Valid Matrix: All Numbers in Rows & Columns INPUT 3x3 Matrix (n=3) 1 2 3 2 3 1 3 1 2 R0 R1 R2 C0 C1 C2 matrix = [ [1,2,3], [2,3,1], [3,1,2] ] ALGORITHM STEPS 1 Initialize Arrays Create n boolean arrays for rows and columns 2 Single Pass Scan For each cell[i][j], mark value as seen Row0: [1,2,3] T T T 3 Check Duplicates If value already seen --> return false 4 Verify Complete All arrays full? --> return true Time: O(n^2) | Space: O(n^2) n rows x n columns arrays FINAL RESULT 1,2,3 OK 2,3,1 OK 3,1,2 OK All rows have 1,2,3 Column Validation: Col0: [1,2,3] OK Col1: [2,3,1] OK Col2: [3,1,2] OK OUTPUT true Matrix is VALID Key Insight: Use boolean arrays to track seen numbers for each row and column separately. For a valid matrix, each row[i] and col[j] array must have all values from 1 to n marked true. If any duplicate is found (already marked true), the matrix is invalid immediately. TutorialsPoint - Check if Every Row and Column Contains All Numbers | Single Pass with Boolean Arrays
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