Archive

LeetCode. 36. Valid Sudoku

Archived technical note: LeetCode. 36. Valid Sudoku.

image

[Link] https://leetcode.com/problems/valid-sudoku/


The board is valid when no filled digit is repeated in any row, column, or 3×3 box. Empty cells (.) are ignored; the partially filled board does not need to be solvable.

Keep one bitmask for each row, column, and box. A digit d maps to 1 << (d - '1'), and the box index for cell (r, c) is (r / 3) * 3 + c / 3. If the bit is already set in any of those three masks, the digit is a duplicate. Otherwise, set it in all three masks.

Each of the 81 cells is processed once, so the time complexity is O(81). The fixed arrays use constant additional space, O(1).

class Solution {
    public boolean isValidSudoku(char[][] board) {
        int[] rows = new int[9];
        int[] columns = new int[9];
        int[] boxes = new int[9];

        for (int r = 0; r < 9; r++) {
            for (int c = 0; c < 9; c++) {
                char value = board[r][c];
                if (value == '.') {
                    continue;
                }

                int bit = 1 << (value - '1');
                int box = (r / 3) * 3 + c / 3;
                if ((rows[r] & bit) != 0
                        || (columns[c] & bit) != 0
                        || (boxes[box] & bit) != 0) {
                    return false;
                }

                rows[r] |= bit;
                columns[c] |= bit;
                boxes[box] |= bit;
            }
        }
        return true;
    }
}