#36
Medium Algorithms Valid sudoku
Array Hash Table Matrix
64.2% acceptance
Jan 12, 2026
12400
1262
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
Note:
A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn is_valid_sudoku(board: Vec<Vec<char>>) -> bool {
use std::collections::HashSet;
let mut rows: Vec<HashSet<char>> = vec![HashSet::new(); 9];
let mut cols: Vec<HashSet<char>> = vec![HashSet::new(); 9];
let mut boxes: Vec<HashSet<char>> = vec![HashSet::new(); 9];
for i in 0..9 {
for j in 0..9 {
let c = board[i][j];
if c == '.' {
continue;
}
// Check row
if rows[i].contains(&c) {
return false;
}
rows[i].insert(c);
// Check column
if cols[j].contains(&c) {
return false;
}
cols[j].insert(c);
// Check 3x3 box
let box_index = (i / 3) * 3 + (j / 3);
if boxes[box_index].contains(&c) {
return false;
}
boxes[box_index].insert(c);
}
}
true
}
}