Check if Every Row and Column Contains All Numbers Visualizer & Step-by-Step Algorithm Solution

An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Check validity using row and column hash sets.

Category: arrays | Difficulty: Easy

Tags: Array, Hash Table, Matrix

Check if Every Row and Column Contains All Numbers

Matrix (3 x 3)
0
1
2
0
1
2
1
2
3
3
1
2
2
3
1
Active Cell
Active Row / Col / Box
Conflict / Subtracted
Highlighted / Subgrid
100%
state
n3
matrix size3 x 3
Initialization
1/59
Explanation

Start checkValid on 3 x 3 matrix. Check if all rows and columns contain integers 1 to 3 without duplicates.

Source Code
1function checkValid(matrix: number[][]): boolean {
2 const row = new Set<number>();
3 const col = new Set<number>();
4 const n = matrix.length;
5 for (let i = 0; i < n; i++) {
6 for (let j = 0; j < n; j++) {
7 if (row.has(matrix[i][j])) return false;
8 if (col.has(matrix[j][i])) return false;
9
10 row.add(matrix[i][j]);
11 col.add(matrix[j][i]);
12 }
13 row.clear();
14 col.clear();
15 }
16 return true;
17}