Valid Sudoku solution explained

The Valid Sudoku solution makes one pass over the 81 cells and, for each filled cell, records its digit against its row, its column and its 3x3 box, using the box index (row // 3) * 3 + column // 3. If any of those three records already holds that digit, the board is invalid. The work is a fixed 81 cells with constant-size memory, and the check is only about repeats among filled cells, not about whether the puzzle can be solved.

By Published 8 min read

The problem in plain words

You are given a 9 by 9 grid. Each cell holds a digit from 1 to 9 or a dot meaning empty. The board is valid if no digit appears twice in the same row, twice in the same column, or twice in the same 3x3 box, where the boxes are the nine non-overlapping 3x3 squares that tile the grid. Empty cells are ignored. You do not need to fill the board or decide whether it can be completed.

......5.2
.....28..
...84.9..
..9.7....
1.....4..
..8439..5
...7.....
....8....
.843.....
A board generated for this page. It is valid: no row, column or box repeats a digit.
Changes to that board and what the check says (verified by running the code)
ChangeValid?Why
NoneYesEvery filled digit is unique in its row, column and box
Put 5 in row 1, column 1 (counting from 1)NoRow 1 already has a 5 in column 7
Put 1 in row 4, column 2NoThe left middle box already has a 1 at row 5, column 1, though neither the row nor the column does
A different board: first row 12345678. and a 9 in row 5, column 9YesNo repeats anywhere, yet the empty cell in row 1 can hold nothing, so the puzzle has no solution
Changes to that board and what the check says (verified by running the code). Scroll sideways on a small screen.

Why it comes up

It is a bookkeeping problem with a fixed size, which makes it a good test of clean code rather than clever algorithms. Interviewers look for three things: that you check all three kinds of unit, that you compute the box index correctly, and that you do not overreach by trying to solve the puzzle. Asking "do you want me to check only the filled cells, or also whether it is solvable?" at the start is a good signal.

Follow-up questions

  • Solve the board. That is backtracking: try digits in an empty cell, use this validity check to prune, and undo on failure. A much bigger problem.
  • Generalize to n² by n² boards. Boxes become n by n, and the box index is (row // n) * n + column // n.
  • Validate a completed board. Same code; additionally every cell must be filled, or each unit must contain all nine digits.
  • Use less memory. Replace each set with a 9-bit mask, so the whole state is 27 small integers.
  • Report where the conflict is. Return the row, column or box and the repeated digit instead of a boolean.

A clear first answer: check each unit

List the 27 units as lists of coordinates: nine rows, nine columns and nine boxes. For each unit, collect the filled digits and compare the count with the size of the set of those digits. If they differ, something repeats. Each cell is looked at three times, so the work is 243 cell reads, which for a fixed board is constant. It is easy to read and easy to get right, and some interviewers are happy to stop here.

def is_valid_by_units(board):
    units = [[(r, c) for c in range(9)] for r in range(9)]            # rows
    units += [[(r, c) for r in range(9)] for c in range(9)]           # columns
    units += [[(top + i, left + j) for i in range(3) for j in range(3)]
              for top in (0, 3, 6) for left in (0, 3, 6)]             # boxes
    for unit in units:
        digits = [board[r][c] for r, c in unit if board[r][c] != "."]
        if len(digits) != len(set(digits)):
            return False
    return True
Unit by unit: 27 duplicate checks.

The one-pass answer

Scan the cells once. For each filled cell at row r and column c, compute its box: the box row is r // 3, the box column is c // 3, and numbering the boxes 0 to 8 left to right and top to bottom gives (r // 3) * 3 + c // 3. Then ask three questions: has this digit already appeared in row r, in column c, or in that box? If yes to any, return false. Otherwise record it in all three. In Python, a single set of tuples such as ("row", r, d) keeps it short; the JavaScript version uses one 9-bit mask per row, column and box, where bit d is set once digit d has been seen.

def is_valid_board(board):
    seen = set()
    for r in range(9):
        for c in range(9):
            d = board[r][c]
            if d == ".":
                continue
            keys = (("row", r, d), ("col", c, d), ("box", r // 3 * 3 + c // 3, d))
            if any(k in seen for k in keys):
                return False
            seen.update(keys)
    return True
Python: one scan, one set of (kind, index, digit) keys.
function isValidBoard(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 d = board[r][c];
      if (d === ".") continue;
      const bit = 1 << Number(d); // one bit per digit 1 to 9
      const b = Math.floor(r / 3) * 3 + Math.floor(c / 3);
      if ((rows[r] | cols[c] | boxes[b]) & bit) return false;
      rows[r] |= bit;
      cols[c] |= bit;
      boxes[b] |= bit;
    }
  }
  return true;
}
JavaScript: bit masks per row, column and box. Works with rows as strings or arrays.

Both versions accept the board as a list of strings or a list of lists, because indexing board[r][c] works for either. Ask which form the interviewer will pass in; some give characters, others give numbers with 0 for empty, which only changes the empty check.

Cost of each approach

For a standard 9x9 board (and an n² by n² generalization)
ApproachTimeExtra memoryNotes
Check each filled cell against its row, column and box81 x 24 reads; O(N^1.5) for N cellsO(1)No extra structures; most repeated work
27 unit checks with a set each243 reads; O(N)O(9) per unitClear and easy to explain
One pass with sets or masks81 reads; O(N)27 sets or 27 masksThe usual final answer
For a standard 9x9 board (and an n² by n² generalization). Scroll sideways on a small screen.

For a fixed 9x9 board every version is technically O(1). Say that, then compare them in terms of how many times each cell is read, which is what actually differs.

Edge cases

  • An empty board: valid.
  • A conflict only inside a box, with the row and column clean. Code that forgets boxes passes it.
  • Two equal digits in the same box but different rows and columns, the case a wrong box formula misses.
  • A board that is valid but unsolvable, to make sure you did not promise more than the check delivers.
  • Input with a different empty marker, such as 0 or a space.

Common slips

  • Computing the box as r // 3 + c // 3, which maps different boxes to the same number. The row part must be multiplied by 3.
  • Counting the empty marker as a digit, so two dots in a row look like a repeat.
  • Using one shared set for rows, columns and boxes without tagging the keys, so a 5 in row 2 collides with a 5 in column 2.
  • Trying to solve the puzzle or check that each unit has all nine digits, which is a different question.
  • In C, C++ or Java, shifting by the character code instead of the digit, since the character 5 has code 53. JavaScript happens to convert the string "5" to the number 5 here, but say so rather than rely on it.

How to explain it out loud

Fictional example

Scoping the problem, then the box formula
Candidate
Just to confirm: I only need to check that filled digits do not repeat, not that the board is solvable, right? Good.
Candidate
I'll scan every cell once. For a filled cell I need to know whether its digit already appeared in its row, its column or its box. The box number is row divided by three, times three, plus column divided by three, using integer division.
Candidate
I'll keep a set for each, or nine-bit masks if memory matters. Each cell is read once, the board is a fixed size, so it is constant time and constant space, and in general linear in the number of cells.

Missing Number looks for a gap where this problem looks for a repeat, and both reward knowing exactly which values should be present. Encode and Decode Strings is another exercise in careful bookkeeping. Number of Islands also walks a grid cell by cell, and Two Sum is the simplest case of "have I seen this before?" with a hash set.

Using Natively to practice

Grid problems are easy to misread under pressure. During practice on Mac or Windows, Natively can read the board and the prompt from a screenshot, check your box formula with a few cells, and point out the box-only conflict your test missed. After a mock round, its transcript shows whether you clarified the difference between valid and solvable at the start.

Questions people ask

How do you check if a Sudoku board is valid?

Scan each filled cell once and record its digit for its row, its column and its 3x3 box, using sets or bit masks. If a digit is already recorded in any of the three, the board is invalid.

How do you find which 3x3 box a cell belongs to?

With integer division: box = (row // 3) * 3 + column // 3, which numbers the nine boxes 0 to 8 from left to right and top to bottom.

Does a valid Sudoku board have to be solvable?

No. The check only looks for repeated digits among filled cells. A board can have no repeats and still have an empty cell where no digit fits, so it cannot be solved.

What is the time complexity of Valid Sudoku?

For a fixed 9x9 board it is constant, since there are always 81 cells. In general it is linear in the number of cells, with one read per cell in the one-pass version.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP