The Problem

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

1. Each row must contain the digits 1-9 without repetition.
2. Each column must contain the digits 1-9 without repetition.
3. 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.

Interactive Visualization

Speed:
Sudoku Board
Tracking Sets
Row Set
Column Set
Box Set
Status
Press Step or Play to begin.
Code
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}

How It Works

Key Insight

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.

The Algorithm

  • Initialize: Create 9 empty sets for rows, 9 for columns, and 9 for boxes.
  • Iterate: For each cell (r, c) in the 9x9 grid:
  • Skip empty: If the cell is '.', continue to the next cell.
  • Compute box index: box_idx = (r // 3) * 3 + c // 3 maps each cell to one of the nine 3x3 boxes (0-8).
  • Check duplicates: If the value is already in rows[r], cols[c], or boxes[box_idx], return False.
  • Record: Add the value to all three sets.
  • Result: If no duplicates found after all cells, return True.

Complexity

Time O(1)
Space O(1)

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.