mediumMatrixHash TableArrays & Hashing

Valid Sudoku

mediumTime: O(1)Space: O(1)

Recognize the pattern

check if 9×9 Sudoku board is validno duplicates in rows, columns, or 3×3 boxesset-based checking

Brute force idea

If you approach Valid Sudoku in the most literal way possible, you get this: For each cell, check its row, column, and box for duplicates — but with redundant checks. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

A calmer way to see Valid Sudoku is this: Three hash sets per row, column, and box (27 total). Single pass through all 81 cells, checking and adding to the appropriate three sets. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Key invariant

The truth you want to protect throughout Valid Sudoku is this: Each number must be unique in its row, column, AND 3×3 box. The box index for cell (r,c) is (r/3)*3 + c/3, mapping each cell to one of 9 boxes. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Watch out for

The trap in Valid Sudoku usually looks like this: Forgetting the box check — row and column uniqueness is obvious, but box uniqueness requires computing which 3×3 region the cell belongs to. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Arrays & Hashing Pattern