Valid Sudoku

Medium Arrays & Hashing Hashing Original on LeetCode

Reported atPayPalZoho

Valid Sudoku is a medium arrays & hashing problem solved with the hashing pattern. The best approach, optimal (one pass with bitmasks), runs in O(N²) time and O(N) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (re-scan for every cell) up.

Problem

You get a 9 x 9 Sudoku board, partly filled with digits '1'–'9'; empty cells are '.'. Decide whether the filled cells are valid so far:

  • no digit appears twice in the same row,
  • no digit appears twice in the same column,
  • no digit appears twice in any of the nine 3 x 3 boxes.

You only check these rules for the digits already on the board. The board does not have to be solvable to count as valid.

Examples

Example 1

Input
board = [["8",".",".",".","4",".",".",".","1"],[".","3",".","9",".",".",".","6","."],[".",".","5",".",".","2","7",".","."],["2",".",".",".",".",".",".",".","9"],[".","6",".",".","5",".",".","3","."],["4",".",".",".",".",".",".",".","7"],[".",".","9","6",".",".","5",".","."],[".","1",".",".",".","8",".","2","."],["7",".",".",".","3",".",".",".","6"]]
Output
true
Why
No digit repeats in any row, any column or any of the nine 3 x 3 boxes.

Example 2

Input
board = [["8",".",".",".","4",".",".",".","1"],[".","3",".","9",".",".",".","6","."],[".","8","5",".",".","2","7",".","."],["2",".",".",".",".",".",".",".","9"],[".","6",".",".","5",".",".","3","."],["4",".",".",".",".",".",".",".","7"],[".",".","9","6",".",".","5",".","."],[".","1",".",".",".","8",".","2","."],["7",".",".",".","3",".",".",".","6"]]
Output
false
Why
Same board, but row 2 now has an 8 in column 1. The top-left 3 x 3 box then contains two 8s.

Constraints

  • board.length == 9 and board[i].length == 9
  • board[i][j] is a digit '1'–'9' or '.' for an empty cell.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (2 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (re-scan for every cell)O(N² · N)O(1)
Optimal (one pass with bitmasks)O(N²)O(N)

1Brute force (re-scan for every cell)

TimeO(N² · N)For each of the 81 cells, about 27 other cells are checked (N = 9).
SpaceO(1)No extra structures.

For each filled cell, look at every other cell in its row, its column and its 3 x 3 box. If any of them holds the same digit, the board is invalid.

  1. For each cell (r, c) holding a digit d:
  2. Scan row r and column c for another cell equal to d.
  3. Scan the 3 x 3 box starting at (r / 3 · 3, c / 3 · 3) for another cell equal to d.
  4. If nothing clashes for any cell, return true.
class Solution {
    public boolean isValidSudoku(char[][] board) {
        for (int r = 0; r < 9; r++) {
            for (int c = 0; c < 9; c++) {
                char d = board[r][c];
                if (d == '.') continue;
                for (int k = 0; k < 9; k++) {
                    if (k != c && board[r][k] == d) return false;
                    if (k != r && board[k][c] == d) return false;
                }
                int br = r / 3 * 3, bc = c / 3 * 3;
                for (int i = br; i < br + 3; i++)
                    for (int j = bc; j < bc + 3; j++)
                        if ((i != r || j != c) && board[i][j] == d) return false;
            }
        }
        return true;
    }
}

2Optimal (one pass with bitmasks)

TimeO(N²)Each of the 81 cells is visited once with O(1) work.
SpaceO(N)27 small integers (N = 9).

Keep one 9-bit mask per row, per column and per box. For each filled cell, compute the bit for its digit; if that bit is already set in its row, column or box mask, a digit repeats. Otherwise set the bit in all three masks and continue.

  1. rows[9], cols[9], boxes[9] all start at 0.
  2. For each filled cell (r, c) with digit d: bit = 1 << (d - '1'), b = (r / 3) * 3 + c / 3.
  3. If rows[r], cols[c] or boxes[b] already has bit, return false.
  4. Set bit in all three masks. After the scan, return true.
class Solution {
    public boolean isValidSudoku(char[][] board) {
        int[] rows = new int[9], cols = new int[9], boxes = new int[9];
        for (int r = 0; r < 9; r++) {
            for (int c = 0; c < 9; c++) {
                if (board[r][c] == '.') continue;
                int bit = 1 << (board[r][c] - '1');
                int b = (r / 3) * 3 + c / 3;
                if ((rows[r] & bit) != 0 || (cols[c] & bit) != 0 || (boxes[b] & bit) != 0) return false;
                rows[r] |= bit;
                cols[c] |= bit;
                boxes[b] |= bit;
            }
        }
        return true;
    }
}

Edge cases to test

  • An empty board (valid)
  • A duplicate that only shows up inside a 3 x 3 box, not in any row or column
  • A board that is valid as it stands even though it has no solution
  • Duplicates in the last row, last column or bottom-right box

Hints

Hint 1

Only the filled cells matter, and only three rules: unique per row, per column and per box.

Hint 2

Cell (r, c) belongs to box (r / 3) * 3 + c / 3.

Hint 3

Keep a 'seen' record for each of the 9 rows, 9 columns and 9 boxes, and fill all of them in one pass over the board.

FAQ

What is the best time complexity for Valid Sudoku?

Optimal (one pass with bitmasks) runs in O(N²) time and O(N) extra space. Each of the 81 cells is visited once with O(1) work.

Which pattern does Valid Sudoku use?

It is a arrays & hashing problem that uses the hashing pattern. Other problems with the same pattern: Group Anagrams, First Unique Character in a String, Number of Matching Subsequences.

Is there a brute force solution for Valid Sudoku?

Yes. Brute force (re-scan for every cell) takes O(N² · N) time and O(1) space. For each filled cell, look at every other cell in its row, its column and its 3 x 3 box.

Which edge cases should I test for Valid Sudoku?

An empty board (valid); A duplicate that only shows up inside a 3 x 3 box, not in any row or column; A board that is valid as it stands even though it has no solution; Duplicates in the last row, last column or bottom-right box.