Valid Sudoku
Last updated
Was this helpful?
Last updated
Was this helpful?
Determine if a 9 x 9
Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
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 digits 1-9
without repetition.
Note: Empty cells consists of '.'(dot) character
We first take note of the above specified properties of a Sudoku. Intuitively, we're thinking about using a Set here since we might have to implement some sort of solution that accounts for duplicates.
The logic is as a follow, if we encode each element that we encounter with their corresponding row -> column -> 3x3 box, we would be able to later verify by using a Set whether they are unique.
For example: (credit: )
'4' in row 7
is encoded as "(4)7"
.
'4' in column 7
is encoded as "7(4)"
.
'4' in the top-right block
is encoded as "0(4)2"
.
Scream false
if we ever fail to add something because it was already added (i.e., seen before).
We iterate thorugh the matrix (board) and we store each non-empty cells values into a set along with their column. row, 3X3 information
The set contains unique values, if the element is already found within the set, by virtue of the above prorperties, the Sudoke in question is not valid.
Time: O(n2) Space: O(distinct(k) k = elements
Time: O(n2) Space: O(distinct(k) k = elements
A different approach we can use if by implementing a method isValid
which takes in coordinates and ensures that the elements within the coordinates are unique. This approach is very intuitive however it can be bit delicate as we have to make sure that the passed coordinates are accurates.
Note: We use ther modulo operator% for 3*3. Because % increments and resets back by staying within the box constraints.