Determine if a 9x9 Sudoku board is valid. A valid board has digits 1-9 appearing at most once per row, per column, and per 3x3 sub-box. Empty cells are marked with '.'. The board may be partially filled — only filled cells must follow the rules.
A brute force approach would scan each row, column, and box separately, requiring three passes over the board. A hash map approach solves it in one pass: as we iterate each cell, we track its digit in three concurrent hash maps — one for the cell's row, one for its column, and one for its 3x3 box. If any digit already exists in the corresponding map, the board is invalid.
The 3x3 box index can be computed from the cell coordinates: boxIndex = floor(row / 3) * 3 + floor(col / 3). This formula maps each cell to one of nine boxes numbered 0 through 8. The algorithm runs in O(81) = O(1) time since the board is always 9x9, and O(1) space (nine hash maps each with at most 9 entries).
Edge cases include an empty board (all '.' — valid), a board with only one row/column conflict, and a board with a box conflict that is not visible in any row or column scan. The one-pass approach catches all three simultaneously.
Example Input & Output
Bottom-left box has two 6s: row 6 col 1 and row 7 col 0.
Duplicate 5 in first row.
Empty board is valid.
Valid board with no conflicts.
Duplicate 8 in first column.
Algorithm Flow

Solution Approach
Create three arrays of 9 hash maps for rows, columns, and boxes. Iterate each cell, compute box index, check for duplicates across all three maps.
Time O(1), Space O(1) — fixed 9x9 board.
Best Answers
import java.util.*;
class Solution {
public boolean solution(char[][] board) {
Map<Integer,Set<Character>> rows = new HashMap<>();
Map<Integer,Set<Character>> cols = new HashMap<>();
Map<Integer,Set<Character>> boxes = new HashMap<>();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char ch = board[i][j];
if (ch == '.') continue;
int b = (i / 3) * 3 + j / 3;
if (rows.computeIfAbsent(i, k -> new HashSet<>()).contains(ch) ||
cols.computeIfAbsent(j, k -> new HashSet<>()).contains(ch) ||
boxes.computeIfAbsent(b, k -> new HashSet<>()).contains(ch)) return false;
rows.get(i).add(ch);
cols.get(j).add(ch);
boxes.get(b).add(ch);
}
}
return true;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
