Skip to main content

Valid Sudoku

Medium
Data Structures and Algorithms
Editorial
Topics:
Array
Matrix
Hash Table

Implement isValidSudoku to determine whether the filled entries in board follow the rules of a 9x9 Sudoku grid. Each cell contains either a digit from '1' through '9' or '.', where '.' means the cell is empty.

Every digit that appears in a row must be different from all other digits in that row. The same requirement applies independently to each column and to each 3x3 subgrid; a subgrid is one of the nine regions formed by three consecutive rows and three consecutive columns.

Return true if no filled digit violates any row, column, or subgrid rule. Return false as soon as any duplicate is found. Empty cells are ignored, and the board does not need to be complete or solvable.

Example 1:

Input: board = [["4",".",".",".","7",".",".",".","."],[".",".","8",".",".",".",".","1","."],[".",".",".","2",".",".","6",".","."],[".","5",".",".",".","9",".",".","."],[".",".","1",".","3",".",".",".","7"],[".",".",".","6",".",".","4",".","."],[".","2",".",".",".",".",".","8","."],[".",".","6",".",".",".","3",".","."],[".",".",".","9",".",".",".",".","5"]]
Output: true
Explanation: Every filled digit is unique within its row, column, and 3x3 subgrid.

Example 2:

Input: board = [["4",".",".",".",".",".",".",".","."],[".","4",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."]]
Output: false
Explanation: The two '4' cells lie in the same upper-left 3x3 subgrid, so that subgrid contains a duplicate.

Example 3:

Input: board = [[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."]]
Output: true
Explanation: There are no filled cells, so no row, column, or subgrid can contain a duplicate.

Constraints:

  • ``board contains exactly 9 rows.
  • Every row in board contains exactly 9 cells.
  • Each cell is a one-character string equal to '.'or one of'1'through'9'.
  • Only filled cells are checked; empty cells represented by '.' impose no restriction.
  • The input board may be incomplete and is not guaranteed to have a solution.

Need help or want more practice?

Practise in an interviewGet AI Coach help