Valid Sudoku
Problem Statement
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: 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:
Hashing
- To ensure the elements in each row, column, square are unique, maintain a set for each
- To track the elements in squares, maintain a
3x3
grid where each cell contains the digits in a square. The square grid cell that an element at[x][y]
index position in input board will go to will be given by calculating[x/3][y/3]
Time
Traversing each cell of board takes \( O(N^2) \) time and each access or insert operation into the hash-set takes \( O(1) \) time on average. Thus, overall time complexity is \( O(N^2) \)
Space
- The row and column sets would have at-most \( N \) elements filled at each of the \( N \) total rows and columns i.e. \( O(N^2) \) space over all elements
- The grid for each square would have dimensions \( \sqrt{N} \ast \sqrt{N} \) and will contain at-most \( N \) elements at each cell of grid i.e. \( O(N^2) \) space over all elements
Metric | Complexity |
---|---|
Time | \( O(N^2 ) \) |
Space | \( O(N^2) \) |