Valid Sudoku
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 3boxes.
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 == 9andboard[i].length == 9board[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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
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.
| Approach | Time | Space |
|---|---|---|
| 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)
O(N² · N)For each of the 81 cells, about 27 other cells are checked (N = 9).O(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.
- For each cell (r, c) holding a digit d:
- Scan row r and column c for another cell equal to d.
- Scan the 3 x 3 box starting at (r / 3 · 3, c / 3 · 3) for another cell equal to d.
- 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;
}
}class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
for r in range(9):
for c in range(9):
d = board[r][c]
if d == ".":
continue
for k in range(9):
if k != c and board[r][k] == d:
return False
if k != r and board[k][c] == d:
return False
br, bc = r // 3 * 3, c // 3 * 3
for i in range(br, br + 3):
for j in range(bc, bc + 3):
if (i != r or j != c) and board[i][j] == d:
return False
return Trueclass Solution {
public:
bool isValidSudoku(vector<vector<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;
}
};function isValidSudoku(board) {
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const d = board[r][c];
if (d === ".") continue;
for (let k = 0; k < 9; k++) {
if (k !== c && board[r][k] === d) return false;
if (k !== r && board[k][c] === d) return false;
}
const br = Math.floor(r / 3) * 3, bc = Math.floor(c / 3) * 3;
for (let i = br; i < br + 3; i++)
for (let j = bc; j < bc + 3; j++)
if ((i !== r || j !== c) && board[i][j] === d) return false;
}
}
return true;
}2Optimal (one pass with bitmasks)
O(N²)Each of the 81 cells is visited once with O(1) work.O(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.
- rows[9], cols[9], boxes[9] all start at 0.
- For each filled cell (r, c) with digit d: bit = 1 << (d - '1'), b = (r / 3) * 3 + c / 3.
- If rows[r], cols[c] or boxes[b] already has bit, return false.
- 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;
}
}class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows, cols, boxes = [0] * 9, [0] * 9, [0] * 9
for r in range(9):
for c in range(9):
ch = board[r][c]
if ch == ".":
continue
bit = 1 << (ord(ch) - ord("1"))
b = (r // 3) * 3 + c // 3
if rows[r] & bit or cols[c] & bit or boxes[b] & bit:
return False
rows[r] |= bit
cols[c] |= bit
boxes[b] |= bit
return Trueclass Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int rows[9] = {0}, cols[9] = {0}, boxes[9] = {0};
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) || (cols[c] & bit) || (boxes[b] & bit)) return false;
rows[r] |= bit;
cols[c] |= bit;
boxes[b] |= bit;
}
}
return true;
}
};function isValidSudoku(board) {
const rows = new Array(9).fill(0), cols = new Array(9).fill(0), boxes = new Array(9).fill(0);
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const ch = board[r][c];
if (ch === ".") continue;
const bit = 1 << (ch.charCodeAt(0) - 49);
const b = Math.floor(r / 3) * 3 + Math.floor(c / 3);
if ((rows[r] & bit) || (cols[c] & bit) || (boxes[b] & bit)) 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.