Determine if a
-
Each row must contain the digits
1-9 without repetition. -
Each column must contain the digits
1-9 without repetition. -
Each of the nine
3 x 3 sub-boxes of the grid must contain the digits1-9 without repetition.
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.
,["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 |
,["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 |
Contents
Solution 1 - Check duplicates using a HashSet
In this approach, we are going to store numbers from the board into a
Inorder to check the duplicates for 3 conditions, we could one
Complexity Analysis:
Time complexity: Above code runs in O(n * m) time where
Space complexity: O(n * m) for the
Above implementations source code can be found at