Valid Sudoku
Determine if a 9 x 9
-
Each row must contain the digits
without repetition.1-9 -
Each column must contain the digits
without repetition.1-9 -
Each of the nine
sub-boxes of the grid must contain the digits3 x 3 without repetition.1-9
Note:
- A Sudoku board (partially filled) could be valid but is not necessarily solvable.
- Only the filled cells need to be validated according to the mentioned rules.
Example 1
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: true
Explanation: Sudoku board will look like below one, and each row, column and 3 X 3 matrix has 1-9 unique values.
| 5 | 3 | 7 | ||||||
| 6 | 1 | 9 | 5 | |||||
| 9 | 8 | 6 | ||||||
| 8 | 6 | 3 | ||||||
| 4 | 8 | 3 | 1 | |||||
| 7 | 2 | 6 | ||||||
| 6 | 2 | 8 | ||||||
| 4 | 1 | 9 | 5 | |||||
| 8 | 7 | 9 |
Example 2
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: false
Explanation: Sudoku board will look like below one, circled 8's in the first 3 X 3 matrix as well as in the 1st column are repeated, so the answer is false in this case.
| 3 | 7 | |||||||
| 6 | 1 | 9 | 5 | |||||
| 9 | 6 | |||||||
| 6 | 3 | |||||||
| 4 | 8 | 3 | 1 | |||||
| 7 | 2 | 6 | ||||||
| 6 | 2 | 8 | ||||||
| 4 | 1 | 9 | 5 | |||||
| 8 | 7 | 9 |
Solution 1 - Check duplicates using a HashSet
In this approach, we are going to store numbers from the board into a HashSet
Inorder to check the duplicates for 3 conditions, we could one HashSetvalue
import java.util.HashSet;
public class ValidSudoku {
static boolean isValidSudoku(char[][] board) {
HashSet<String> set = new HashSet<>(9 * 9);
for(int i=0; i< board.length; i++) {
for(int j=0; j<board[i].length; j++) {
if(board[i][j] == '.') {
continue;
}
// check if the number seen in the same row
if(!set.add("ROW : "+i+ " NUM :"+board[i][j])) {
return false;
}
// check if the number seen in the same row
if(!set.add("COLUMN : "+j+ " NUM :"+board[i][j])) {
return false;
}
// check if the number seen in the 3 X 3 matrix that the current cell is in
// use i/3 and j/3 to get the current that matrix
if(!set.add("ROW :"+ i/3 +"COLUMN : "+ j/3 + " NUM :"+board[i][j])) {
return false;
}
}
}
return true;
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n * m) time where nboardmboard
Space complexity: O(n * m) for the HashSet
Above implementations source code can be found at