Valid Sudoku
mediumNeetCode 150arrayshashingmatrix
Problem
Given a partially filled 9x9 grid, decide whether the current placement is valid. Each row, each column, and each of the nine 3x3 sub-boxes must contain no repeated digit. Empty cells are ignored.
Examples
Input: A board where row 0 has two 8s
Output: false
A digit repeats within a single row.
Input: A standard valid partial board
Output: true
No row, column, or box has a repeat.
Constraints
- • Board is 9x9
- • Cells hold digits 1-9 or an empty marker
- • Only current placement is checked, not solvability
Hints(tap to reveal)
- 1. Track seen digits per row, per column, and per box.
- 2. Box index can be derived from row/3 and col/3.
Optimal approach(spoiler)
- Keep a set of seen digits for each row, each column, and each 3x3 box.
- Compute the box key from the integer division of the row and column by three.
- For each filled cell, check all three sets for a conflict.
- Insert the digit into each set after checking.
- Single pass over 81 cells, effectively O(1).
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor