An interactive visualization of the hash-set approach to validating a 9x9 Sudoku board. Watch how sets track seen digits per row, column, and 3x3 box.
Hash Map LeetCode 36 ↗ Medium9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:1-9 without repetition.1-9 without repetition.3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.fun isValidSudoku(board: Array<CharArray>): Boolean { val rows = Array(9) { mutableSetOf<Char>() } val cols = Array(9) { mutableSetOf<Char>() } val boxes = Array(9) { mutableSetOf<Char>() } for (r in 0 until 9) { for (c in 0 until 9) { val v = board[r][c] if (v == '.') // skip empty continue val boxIdx = (r / 3) * 3 + c / 3 if (v in rows[r] || v in cols[c] || v in boxes[boxIdx]) { return false } rows[r].add(v) cols[c].add(v) boxes[boxIdx].add(v) } } return true}
Use three arrays of sets to track which digits have been seen in each row, each column, and each 3x3 box. For every filled cell, check if its value already exists in the corresponding row set, column set, or box set. If a duplicate is found, the board is invalid. Otherwise, add the value to all three sets and continue.
(r, c) in the 9x9 grid:'.', continue to the next cell.box_idx = (r // 3) * 3 + c // 3 maps each cell to one of the nine 3x3 boxes (0-8).rows[r], cols[c], or boxes[box_idx], return False.True.The board is always 9x9 = 81 cells, so we always iterate a fixed number of times. The sets hold at most 9 values each (27 sets total), so space is also constant. Both are technically O(81) = O(1) since the board size is fixed.