Empty cells are skipped
Empty cells carry no value that could conflict. Including them would be meaningless — we only validate filled digits.
A puzzle app validates a player's partially filled Sudoku board before accepting a submission. Each row, each column, and each 3×3 sub-box must contain the digits 1–9 without repetition — empty cells are placeholders and ignored entirely. Three sets of hash tables (one per dimension) and a single linear scan over all 81 cells detect any rule violation. O(1) time and O(1) space — the board size is fixed.
We maintain three arrays of hash sets — rowDigits[9], columnDigits[9], and boxDigits[9] — 27 sets in total. As we scan each filled cell, we check whether its digit already exists in the corresponding row set, column set, or box set. If any of the three contains it, we have found a duplicate and the board is invalid. Otherwise we add the digit to all three sets and move on.
A single scan through all 81 cells, checking each filled digit against three hash sets — one per dimension. The box index is computed as (row / 3) × 3 + (col / 3).
Initialize rowDigits[9], colDigits[9], and boxDigits[9] — one set per row, column, and 3×3 box.
Skip empty cells ('.'). For each digit, compute its row, column, and box index.
If the digit already exists in any of the three corresponding sets, the board is invalid — stop immediately.
If no conflict, add the digit to all three sets and continue to the next cell.
Understanding boundary behavior is as important as the main algorithm path.
Empty cells carry no value that could conflict. Including them would be meaningless — we only validate filled digits.
A single duplicate is enough to declare the board invalid. There is no reason to continue scanning once a conflict is found.
Time: O(1) — the board is always 9×9, so we
visit at most 81 cells regardless of input.
Space: O(1) — 27 hash sets each holding at
most 9 digits, bounded by a constant.