Valid Sudoku

Medium Hash SetMatrixArray

Problem

Determine if a 9×9 Sudoku board is valid. Only the filled cells need to be checked: no digit may repeat within a row, a column, or any of the nine 3×3 sub-boxes. Empty cells are marked with . and the board does not have to be solvable.

Example 1 Input: board has 5,3 then 7 in row 0; all rows/cols/boxes consistent Output: true
Example 2 Input: same board but the top-left 5 is changed to 8 (two 8s in column 0 / box 0) Output: false

Constraints

Approach — Hashing & Counting

This is a Hashing & Counting problem. The idea: store what you've seen in a hash map for O(1) lookups, trading a little space to avoid a nested scan. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(n) space.

Solution code

Python

class Solution:
    def isValidSudoku(self, board):
        rows = [set() for _ in range(9)]
        cols = [set() for _ in range(9)]
        boxes = [set() for _ in range(9)]
        for r in range(9):
            for c in range(9):
                v = board[r][c]
                if v == '.':
                    continue
                b = (r // 3) * 3 + c // 3
                if v in rows[r] or v in cols[c] or v in boxes[b]:
                    return False
                rows[r].add(v); cols[c].add(v); boxes[b].add(v)
        return True

Java

class Solution {
    public boolean isValidSudoku(char[][] board) {
        Set<String> seen = new HashSet<>();
        for (int r = 0; r < 9; r++) {
            for (int c = 0; c < 9; c++) {
                char v = board[r][c];
                if (v == '.') continue;
                if (!seen.add("row" + r + "#" + v)
                 || !seen.add("col" + c + "#" + v)
                 || !seen.add("box" + (r / 3) + (c / 3) + "#" + v)) {
                    return false;
                }
            }
        }
        return true;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Valid Sudoku interactively → ← All solutions