36/670

36. Valid Sudoku

Medium

A 9×9 sudoku board arrives as a list board of nine strings, each nine characters long: the digits 19 for filled cells and . for blanks. Decide whether the filled cells are consistent with sudoku's rules — no digit may occur twice in any row, twice in any column, or twice inside any of the nine 3×3 boxes.

Only the cells that are already filled matter: a board can be valid without being solvable, because you are checking consistency, not completing the puzzle. Return true when every filled cell obeys all three rules and false otherwise.

One duplicate anywhere invalidates the boardTwo 2s share the top-middle 3×3 box (gold). They sit in different rows and different columns, yet the box rule alone makes the board invalid.
5868356369874576135691522

Example 1:

Input: board = ["..5286...", ".8.3...56", "36951....", "..87....2", "457......", "6..1.957.", ".3.....65", "5..6...29", "91..5.8.7"]

Output: true

Explanation: Every filled digit is unique within its row, its column, and its 3×3 box, so the configuration is valid.

Example 2:

Input: board = ["..5286...", ".8.3...56", "36951....", "..87....2", "457....4.", "6..1.957.", ".3.....65", "5..6...29", "91..5.8.7"]

Output: false

Explanation: The fifth row contains the digit 4 twice (columns 1 and 8), which breaks the row rule — one violation is enough.

Constraints:

  • board has exactly 9 rows and 9 columns.
  • board[r][c] is a digit '1'-'9' or '.'.
  • Validity is judged only on the filled cells — the board does not need to be solvable.

Hints:

You never have to solve the puzzle. Twenty-seven small checks — 9 rows, 9 columns, 9 boxes — each asking "do the filled cells repeat?" settle the answer.

Cell (r, c) belongs to box (r / 3) * 3 + c / 3 using integer division. Keep one seen-set per row, per column, and per box, and a single pass over the 81 cells detects any duplicate the moment it appears.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: board = ["..5286...", ".8.3...56", "36951....", "..87....2", "457......", "6..1.957.", ".3.....65", "5..6...29", "91..5.8.7"]

Expected output: true