15% off all plans & roadmaps Use code
See plansValid Sudoku
Updated
TL;DR: Check a partly filled 9x9 Sudoku board for duplicate digits in any row, column, or 3x3 box. Walk the grid once and record each digit's presence per row, column, and box, ideally as a bitmask.
Problem
Implement isValidSudoku to decide whether the filled cells of a 9x9 Sudoku board obey the Sudoku rules. Each cell holds a digit from '1' to '9', or '.' if the cell is empty.
A digit may appear at most once in each row. The same holds for each column and for each of the nine 3x3 subgrids, where a subgrid is made of three consecutive rows and three consecutive columns.
Return true if no filled digit breaks any of these rules, and false otherwise. Empty cells are ignored. The board may be incomplete, and it does not have to be solvable.
Example 1
Input: board = [["4",".",".",".","7",".",".",".","."],[".",".","8",".",".",".",".","1","."],[".",".",".","2",".",".","6",".","."],[".","5",".",".",".","9",".",".","."],[".",".","1",".","3",".",".",".","7"],[".",".",".","6",".",".","4",".","."],[".","2",".",".",".",".",".","8","."],[".",".","6",".",".",".","3",".","."],[".",".",".","9",".",".",".",".","5"]] Output: true Explanation: Every filled digit is unique within its row, column, and 3x3 subgrid.
Example 2
Input: board = [["4",".",".",".",".",".",".",".","."],[".","4",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."]] Output: false Explanation: The two '4' cells sit in the same upper-left 3x3 subgrid, so that subgrid holds a duplicate.
Example 3
Input: board = a 9x9 grid where every cell is "." Output: true Explanation: No cell is filled, so no row, column, or subgrid can contain a duplicate.
Constraints
boardhas exactly 9 rows.- Every row has exactly 9 cells.
- Each cell is a one-character string:
'.'or a digit from'1'to'9'. - Only filled cells are checked. Empty cells impose no restriction.
- The board may be incomplete and is not guaranteed to have a solution.
Constraints that matter
- The board is always 9x9, so there are exactly 81 cells. Even an O(n^3) scan is about 2,000 reads, so brute force passes. The interview question is about doing it cleanly.
- Digits come from a fixed alphabet of nine values. That lets you replace a hash set with a 9-bit mask or a boolean array of size 9.
- Only filled cells matter and the board need not be solvable. You check for current duplicates only. You never search for a solution, so no backtracking is needed.
- Cells are strings, not integers. You must convert a character to a digit index, or compare strings directly, and you must skip the
"."marker.
Hints
Hint 1
This is a previously-seen check, the hashing pattern.
Hint 2
For every filled cell, rescan its whole row, its whole column, and its whole 3x3 box looking for another cell with the same digit.
Solution
Intuition
This is a previously-seen check, the hashing pattern. A board is invalid exactly when some digit shows up a second time inside one row, one column, or one box. So while you scan, you only need to remember which digits each of those 27 regions has already contained.
It is like a clipboard with nine checkboxes for each row, column, and box. Each digit is one checkbox, and the bitmask is the set of boxes already ticked, so ticking an already ticked box means a duplicate.
Every filled cell belongs to three regions at once. Its row is its row index, its column is its column index, and its box is (r / 3) * 3 + (c / 3) with integer division. Keep one record per region, and a cell is legal only if its digit is absent from all three records.
A duplicate in a region means two cells share a digit and a region. Whichever of the two cells you reach second will find the digit already recorded. So one pass in any order catches every violation, and you can stop at the first.
Because the digits are only 1 to 9, each record can be a single integer used as a bit set. Bit d - 1 is on when digit d has been seen. That is the same idea as a hash set with less overhead.
Worked example
Input: board = [["4",".",".",".","7",".",".",".","."],[".",".","8",".",".",".",".","1","."],[".",".",".","2",".",".","6",".","."],[".","5",".",".",".","9",".",".","."],[".",".","1",".","3",".",".",".","7"],[".",".",".","6",".",".","4",".","."],[".","2",".",".",".",".",".","8","."],[".",".","6",".",".",".","3",".","."],[".",".",".","9",".",".",".",".","5"]] Output: true Explanation: The board has 19 filled cells. Scanned row by row, each digit is new to its row, its column, and its box, so no scan ever finds a repeat and the answer is true.
Approach 1: Brute force
For every filled cell, rescan its whole row, its whole column, and its whole 3x3 box looking for another cell with the same digit. If any other cell matches, the board is invalid. This is the rule from the statement, applied literally, with no memory between cells.
Steps
- Loop over every cell
(r, c)and skip it if it holds'.'. - Scan the nine cells of row
r. If a cell other than(r, c)holds the same digit, return false. - Scan the nine cells of column
cthe same way. - Find the box corner with
r / 3 * 3andc / 3 * 3, then scan its nine cells, ignoring(r, c)itself. - If no scan finds a match for any cell, return true.
Dry run
Take the example board. Cell (0,0) holds 4. Row 0 has only 4 and 7, so no second 4. Column 0 is all dots below it.
Box 0 holds 4 and 8, so still no second 4, and the cell passes. Cell (0,4) holds 7. Row 0 has one 7, column 4 has 7 and 3, and box 1 has 7 and 2, so it passes.
The same three scans run for each of the 19 filled cells, and none finds an equal digit elsewhere. After the last cell, (8,8) holding 5, the function returns true.
Complexity
| Time | O(n^3) |
|---|---|
| Space | O(1) |
Here n is the board side, 9. There are n^2 cells, and each filled cell reads up to 3n cells (a row, a column, and a box of n cells). That gives at most 3 * n^3 reads, about 2,187 for 9x9, and it stays O(n^3) as n grows. It stores nothing beyond a few loop variables, so space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
for r in range(9):
for c in range(9):
v = board[r][c]
if v == '.':
continue
for k in range(9):
# same row, different column
if k != c and board[r][k] == v:
return False
# same column, different row
if k != r and board[k][c] == v:
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, j) != (r, c) and board[i][j] == v:
return False
return TrueJavaTested in our runner
import java.util.*;
class Solution {
public boolean isValidSudoku(String[][] board) {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
String v = board[r][c];
if (v.equals(".")) continue;
for (int k = 0; k < 9; k++) {
if (k != c && board[r][k].equals(v)) return false;
if (k != r && board[k][c].equals(v)) 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].equals(v)) return false;
}
}
}
}
return true;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
bool isValidSudoku(vector<vector<string>>& board) {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
const string& v = board[r][c];
if (v == ".") continue;
for (int k = 0; k < 9; k++) {
if (k != c && board[r][k] == v) return false;
if (k != r && board[k][c] == v) 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] == v) return false;
}
}
}
}
return true;
}
};JavaScriptTested in our runner
/**
* @param {string[][]} board
* @return {boolean}
*/
var isValidSudoku = function(board) {
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const v = board[r][c];
if (v === '.') continue;
for (let k = 0; k < 9; k++) {
if (k !== c && board[r][k] === v) return false;
if (k !== r && board[k][c] === v) return false;
}
const br = Math.floor(r / 3) * 3;
const 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] === v) return false;
}
}
}
}
return true;
};GoTested in our runner
func isValidSudoku(board [][]string) bool {
for r := 0; r < 9; r++ {
for c := 0; c < 9; c++ {
v := board[r][c]
if v == "." {
continue
}
for k := 0; k < 9; k++ {
if k != c && board[r][k] == v {
return false
}
if k != r && board[k][c] == v {
return false
}
}
br, bc := r/3*3, c/3*3
for i := br; i < br+3; i++ {
for j := bc; j < bc+3; j++ {
if (i != r || j != c) && board[i][j] == v {
return false
}
}
}
}
}
return true
}C#Tested in our runner
public class Solution {
public bool isValidSudoku(string[][] board) {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
string v = board[r][c];
if (v == ".") continue;
for (int k = 0; k < 9; k++) {
if (k != c && board[r][k] == v) return false;
if (k != r && board[k][c] == v) 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] == v) return false;
}
}
}
}
return true;
}
}
Solution pattern
Hashing - Previously Seen / Existence Check
Approach 2: One-pass hash setsHashing - Previously Seen / Existence Check
What's slow: the brute force rereads the same row, column, and box for every cell in them. A row of nine filled cells is scanned nine times. The comparisons repeat work that a single memory could answer.
The insight that fixes it: keep nine sets for rows, nine for columns, and nine for boxes. Each set holds the digits already seen in that region. A membership test replaces the 27-cell rescan, so each cell costs a handful of constant-time operations.
Steps
- Create three arrays of nine empty sets:
rows,cols,boxes. - Visit cells in row-major order and skip
'.'. - Compute the box index as
(r / 3) * 3 + (c / 3). - If the digit is already in
rows[r],cols[c], orboxes[b], return false. - Otherwise add the digit to all three sets.
- After all 81 cells, return true.
Dry run
On the example board, the sets fill as you scan. After (0,0)=4 the row 0 set is {4}, column 0 is {4}, and box 0 is {4}. After (0,4)=7, row 0 is {4,7}, column 4 is {7}, box 1 is {7}.
At (1,2)=8 the box index is (1/3)*3 + 2/3 = 0, and box 0 becomes {4,8}. At (4,2)=1, column 2 is {8} and gains 1, giving {1,8}, while box 3 holds {5} and becomes {1,5}. Every membership test comes back empty through the last cell (8,8)=5, and the function returns true.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(n^2) |
Here n is the board side, 9. The loop visits n^2 cells and does at most three lookups and three inserts per cell, each O(1) on average. The sets together hold at most 3 * n^2 digits, which is 243 entries for 9x9. Both bounds are constants for the fixed board, and the formulas show how they grow if the grid grows.
PythonTested in our runner
from typing import List, Optional
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
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
# check before inserting, or every digit looks like a duplicate
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 TrueJavaTested in our runner
import java.util.*;
class Solution {
public boolean isValidSudoku(String[][] board) {
List<Set<String>> rows = new ArrayList<>();
List<Set<String>> cols = new ArrayList<>();
List<Set<String>> boxes = new ArrayList<>();
for (int i = 0; i < 9; i++) {
rows.add(new HashSet<>());
cols.add(new HashSet<>());
boxes.add(new HashSet<>());
}
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
String v = board[r][c];
if (v.equals(".")) continue;
int b = (r / 3) * 3 + c / 3;
if (rows.get(r).contains(v) || cols.get(c).contains(v) || boxes.get(b).contains(v)) {
return false;
}
rows.get(r).add(v);
cols.get(c).add(v);
boxes.get(b).add(v);
}
}
return true;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
bool isValidSudoku(vector<vector<string>>& board) {
vector<unordered_set<string>> rows(9), cols(9), boxes(9);
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
const string& v = board[r][c];
if (v == ".") continue;
int b = (r / 3) * 3 + c / 3;
if (rows[r].count(v) || cols[c].count(v) || boxes[b].count(v)) {
return false;
}
rows[r].insert(v);
cols[c].insert(v);
boxes[b].insert(v);
}
}
return true;
}
};JavaScriptTested in our runner
/**
* @param {string[][]} board
* @return {boolean}
*/
var isValidSudoku = function(board) {
const rows = Array.from({ length: 9 }, () => new Set());
const cols = Array.from({ length: 9 }, () => new Set());
const boxes = Array.from({ length: 9 }, () => new Set());
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const v = board[r][c];
if (v === '.') continue;
const b = Math.floor(r / 3) * 3 + Math.floor(c / 3);
if (rows[r].has(v) || cols[c].has(v) || boxes[b].has(v)) {
return false;
}
rows[r].add(v);
cols[c].add(v);
boxes[b].add(v);
}
}
return true;
};GoTested in our runner
func isValidSudoku(board [][]string) bool {
var rows, cols, boxes [9]map[string]bool
for i := 0; i < 9; i++ {
rows[i] = map[string]bool{}
cols[i] = map[string]bool{}
boxes[i] = map[string]bool{}
}
for r := 0; r < 9; r++ {
for c := 0; c < 9; c++ {
v := board[r][c]
if v == "." {
continue
}
b := (r/3)*3 + c/3
if rows[r][v] || cols[c][v] || boxes[b][v] {
return false
}
rows[r][v] = true
cols[c][v] = true
boxes[b][v] = true
}
}
return true
}C#Tested in our runner
public class Solution {
public bool isValidSudoku(string[][] board) {
var rows = new HashSet<string>[9];
var cols = new HashSet<string>[9];
var boxes = new HashSet<string>[9];
for (int i = 0; i < 9; i++) {
rows[i] = new HashSet<string>();
cols[i] = new HashSet<string>();
boxes[i] = new HashSet<string>();
}
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
string v = board[r][c];
if (v == ".") continue;
int b = (r / 3) * 3 + c / 3;
if (rows[r].Contains(v) || cols[c].Contains(v) || boxes[b].Contains(v)) {
return false;
}
rows[r].Add(v);
cols[c].Add(v);
boxes[b].Add(v);
}
}
return true;
}
}Approach 3: One-pass bitmaskOptimal
What's slow: the hash sets work, but each one allocates memory and hashes strings. Most of that machinery is wasted, because the only possible values are the digits 1 to 9.
The insight that fixes it: store each region as one integer used as a 9-bit set. Digit d maps to bit d - 1. Testing membership is mask & bit, and inserting is mask |= bit. The 27 regions become three arrays of nine integers.
Steps
- Create
rows,cols, andboxes, each an array of nine integers set to 0. - Visit every cell in row-major order and skip
'.'. - Turn the character into a bit with
1 << (digit - 1). - Compute the box index as
(r / 3) * 3 + (c / 3). - If
rows[r],cols[c], orboxes[b]already has that bit set, return false. - Otherwise OR the bit into all three masks, and return true after the last cell.
Dry run
The table lists the 19 filled cells of the example in scan order. Each digit set shows the region after the update. No row shows a clash, because the bit was off in all three masks before the update.
| Step | Cell | Digit | Box | rows[r] | cols[c] | boxes[b] | Clash |
|---|---|---|---|---|---|---|---|
| 1 | (0,0) | 4 | 0 | {4} | {4} | {4} | no |
| 2 | (0,4) | 7 | 1 | {4,7} | {7} | {7} | no |
| 3 | (1,2) | 8 | 0 | {8} | {8} | {4,8} | no |
| 4 | (1,7) | 1 | 2 | {1,8} | {1} | {1} | no |
| 5 | (2,3) | 2 | 1 | {2} | {2} | {2,7} | no |
| 6 | (2,6) | 6 | 2 | {2,6} | {6} | {1,6} | no |
| 7 | (3,1) | 5 | 3 | {5} | {5} | {5} | no |
| 8 | (3,5) | 9 | 4 | {5,9} | {9} | {9} | no |
| 9 | (4,2) | 1 | 3 | {1} | {1,8} | {1,5} | no |
| 10 | (4,4) | 3 | 4 | {1,3} | {3,7} | {3,9} | no |
| 11 | (4,8) | 7 | 5 | {1,3,7} | {7} | {7} | no |
| 12 | (5,3) | 6 | 4 | {6} | {2,6} | {3,6,9} | no |
| 13 | (5,6) | 4 | 5 | {4,6} | {4,6} | {4,7} | no |
| 14 | (6,1) | 2 | 6 | {2} | {2,5} | {2} | no |
| 15 | (6,7) | 8 | 8 | {2,8} | {1,8} | {8} | no |
| 16 | (7,2) | 6 | 6 | {6} | {1,6,8} | {2,6} | no |
| 17 | (7,6) | 3 | 8 | {3,6} | {3,4,6} | {3,8} | no |
| 18 | (8,3) | 9 | 7 | {9} | {2,6,9} | {9} | no |
| 19 | (8,8) | 5 | 8 | {5,9} | {5,7} | {3,5,8} | no |
All 19 steps pass, so the loop ends and the function returns true.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(n) |
Here n is the board side, 9. The loop visits n^2 cells and does a fixed number of bit operations on each, so time is O(n^2), which is 81 steps for 9x9. The memory is three arrays of n integers, so 3n integers in total, which is O(n). For the fixed board that is 27 integers, a constant.
PythonTested in our runner
from typing import List, Optional
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = [0] * 9
cols = [0] * 9
boxes = [0] * 9
for r in range(9):
for c in range(9):
v = board[r][c]
if v == '.':
continue
bit = 1 << (int(v) - 1) # digit d uses bit d - 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 TrueJavaTested in our runner
import java.util.*;
class Solution {
public boolean isValidSudoku(String[][] board) {
int[] rows = new int[9];
int[] cols = new int[9];
int[] boxes = new int[9];
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
String v = board[r][c];
if (v.equals(".")) continue;
int bit = 1 << (v.charAt(0) - '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;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
bool isValidSudoku(vector<vector<string>>& 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++) {
const string& v = board[r][c];
if (v == ".") continue;
int bit = 1 << (v[0] - '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;
}
};JavaScriptTested in our runner
/**
* @param {string[][]} board
* @return {boolean}
*/
var isValidSudoku = function(board) {
const rows = new Array(9).fill(0);
const cols = new Array(9).fill(0);
const boxes = new Array(9).fill(0);
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const v = board[r][c];
if (v === '.') continue;
const bit = 1 << (v.charCodeAt(0) - 49); // '1' is code 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;
};GoTested in our runner
func isValidSudoku(board [][]string) bool {
var rows, cols, boxes [9]int
for r := 0; r < 9; r++ {
for c := 0; c < 9; c++ {
v := board[r][c]
if v == "." {
continue
}
bit := 1 << uint(v[0]-'1')
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
}C#Tested in our runner
public class Solution {
public bool isValidSudoku(string[][] board) {
int[] rows = new int[9];
int[] cols = new int[9];
int[] boxes = new int[9];
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
string v = board[r][c];
if (v == ".") continue;
int bit = 1 << (v[0] - '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;
}
}Common mistakes
- Inserting before checking, as in
rows[r].add(v)placed above theif v in rows[r]test. Every digit then finds itself and the function returns false on valid boards. Check all three regions first, then insert. - Using the wrong box index, such as
r // 3 + c // 3or(r + c) // 3. Different boxes then share an index and valid boards fail. Use(r // 3) * 3 + c // 3, which gives 0 to 8. - Forgetting to skip
'.'. Adding the dot to the sets makes the second empty cell in a row look like a duplicate. Addif v == '.': continuebefore any lookup. - Shifting by the digit itself, as in
1 << dinstead of1 << (d - 1), or indexing a size-9 array withd. Digit 9 then lands on bit 9 or index 9, which is out of range for a 9-element array. Subtract 1, or size the array to 10. - Trying to solve the puzzle. Some people add backtracking because the problem says Sudoku. You only validate the filled cells, so a board that has no solution can still return true.
- Brute-force scans that compare a cell with itself, for example
board[r][k] == vwithoutk != c. Every cell then matches itself and returns false. Skip the cell's own position in all three scans.
Edge cases
- An entirely empty board returns true, since no digit can be duplicated.
- Two equal digits in one row, such as
4at (0,0) and (0,8), return false even if the columns and boxes differ. - Two equal digits in one column only, for example (0,0) and (8,0), return false.
- Two equal digits in one box only, such as (0,0) and (1,1), return false even though their rows and columns differ. This is Example 2.
- The same digit in different boxes, rows, and columns, such as
5at (0,0) and (4,4), is valid and returns true. - A single filled cell, or a board with a digit in the very last cell (8,8), returns true. This checks that the box index for the corner is 8, not 9.
Follow-ups interviewers ask
- Why not use one global set for the whole board?
- A digit may legally appear in different rows, columns, and boxes. A global set would reject a valid board the moment a digit repeats anywhere. You need separate records per region, so the check stays local to the three regions a cell belongs to.
- Can you do it with a single hash set instead of 27 sets?
- Yes. Store encoded keys such as
'4 in row 0','4 in col 0', and'4 in box 0'in one set. Ifaddfails for any of the three keys, there is a duplicate. It is the same logic with one container, but the string keys cost more than a bitmask. - How would you handle a generalized n x n board?
- Use a mask or boolean array of size n per region and a box side of sqrt(n). The box index becomes
(r / s) * s + c / swiths = sqrt(n). Time is O(n^2) and space is O(n) with masks. For n above 32 or 64 an integer mask no longer fits, so use a bitset or boolean arrays.
Valid Sudoku FAQ
What is the time complexity of Valid Sudoku?
The one-pass solution visits each of the 81 cells once and does constant work per cell, so it is O(n^2) for an n x n board, which is O(1) for the fixed 9x9 grid. The brute force is O(n^3) because each cell rescans a row, a column, and a box.
Why use a hash set or bitmask for Valid Sudoku?
A duplicate means a digit was already seen in the same row, column, or box. A set or bitmask answers that question in constant time. That removes the repeated rescans and lets one pass finish the job.
Can Valid Sudoku be solved in O(1) extra space?
For the fixed 9x9 board, every solution uses O(1) space, since 27 integers or 243 set entries is a constant. For a general n x n board, the one-pass methods need O(n) with bitmasks. The brute force needs only O(1) extra space, at the cost of O(n^3) time.
How do you find which 3x3 box a cell belongs to?
Use (r // 3) * 3 + (c // 3) with integer division. Rows 0 to 2 give block row 0, rows 3 to 5 give 1, and rows 6 to 8 give 2. Multiplying by 3 and adding the block column gives box indices 0 to 8.
Does a valid Sudoku board have to be solvable?
No. The problem only asks whether the filled cells break a rule right now. A board can pass validation and still have no solution, so you never need backtracking in LeetCode 36.
Why does the bitmask solution use digit minus 1 as the shift?
Digits run from 1 to 9, and a 9-bit mask needs bits 0 to 8. Shifting by digit minus 1 maps '1' to bit 0 and '9' to bit 8. In most languages you can compute this as the character minus '1'.
Asked at
See which companies ask this — Pro
Related problems
- Longest Substring Without Repeating Characters · same technique: Hashing - Previously Seen / Existence Check
- Longest Consecutive Sequence · same technique: Hashing - Previously Seen / Existence Check
- Find the Duplicate Number · same technique: Hashing - Previously Seen / Existence Check
- Contains Duplicate · same technique: Hashing - Previously Seen / Existence Check
- Happy Number · same technique: Hashing - Previously Seen / Existence Check
- First Missing Positive · next harder, same pattern
- Group Anagrams · same pattern: Array/Matrix Manipulation Patterns
- Top K Frequent Elements · same pattern: Array/Matrix Manipulation Patterns
- Task Scheduler · same pattern: Array/Matrix Manipulation Patterns
- Product of Array Except Self · same pattern: Array/Matrix Manipulation Patterns