Sudoku Solver solution explained

To solve a Sudoku in code, use backtracking with constant-time constraint checks: keep, for every row, column and 3 by 3 box, the set of digits already used, then fill empty cells one at a time, trying only digits that none of the three sets contain, and undo a choice when it leads to a dead end. Choosing the empty cell with the fewest legal digits first, rather than the next cell in reading order, cuts the search sharply. Bitmasks make each check a single AND.

By Published 9 min read

The problem, in plain terms

You get a 9 by 9 grid of characters. Some cells hold a digit from 1 to 9, the rest hold a dot meaning empty. Fill the empty cells so that every row, every column and every one of the nine 3 by 3 boxes contains each digit exactly once. The grid is modified in place. Usually you are told the puzzle has exactly one solution; ask, and also ask what to do if the givens already conflict or the puzzle has no solution.

. . . . 3 . . . 1        2 8 7 5 3 4 9 6 1
. 4 . 9 . . 2 . .        5 4 3 9 1 6 2 8 7
9 . . . 7 8 . . .        9 6 1 2 7 8 5 4 3
6 . 2 . . . 4 . .        6 1 2 8 5 7 4 3 9
. . 5 . . . . 1 2        8 7 5 4 9 3 6 1 2
4 3 . . . . . 7 .        4 3 9 6 2 1 8 7 5
. 9 . 1 8 . . 5 .        3 9 6 1 8 2 7 5 4
. . . . . . . 9 .        1 2 8 7 4 5 3 9 6
7 5 4 . . . . . .        7 5 4 3 6 9 1 2 8
A puzzle generated for this page (56 blanks, one solution) and its solution

Why this is an interview question

Sudoku is a compact test of backtracking discipline. You have to represent constraints, choose what to try next, apply a choice, recurse, and undo the choice exactly. Interviewers watch for clean state handling more than cleverness. Mention early that checking whether a grid is valid is a separate, easier problem; solving builds on the same row, column and box bookkeeping.

Brute force and why it is hopeless

The naive approach tries all nine digits in every blank and checks the whole grid at the end. With 56 blanks that is 9^56 combinations, so it never finishes. The first improvement is to check constraints as you place each digit and back out immediately on a conflict. A further one is to make each check fast. Scanning a row, a column and a box costs 27 reads per digit; keeping per-row, per-column and per-box sets makes it O(1).

Backtracking with constraint sets

Read the grid once and record which digits each row, column and box already holds, plus a list of empty cells. The box for row r and column c is r // 3 × 3 + c // 3, numbering boxes 0 to 8 left to right, top to bottom. Then search: pick an empty cell, compute the digits none of its three sets contain, and try each. Placing a digit adds it to the three sets; undoing removes it and resets the cell.

Which empty cell to pick matters a lot. Reading order is simple. Picking the cell with the fewest legal digits, often called the minimum remaining values heuristic, means a cell with one option gets filled at once and a cell with zero options exposes a dead end immediately. On the example puzzle, the reading-order search made 3,567 recursive calls and the fewest-options search made 57. Over 25 generated puzzles the totals were 1,081,650 and 8,402. Each fewest-options call does more work, since it scans every empty cell, but the trade is strongly worth it.

def solve_sudoku(board):
    rows = [set() for _ in range(9)]
    cols = [set() for _ in range(9)]
    boxes = [set() for _ in range(9)]
    empty = []
    for r in range(9):
        for c in range(9):
            d = board[r][c]
            if d == ".":
                empty.append((r, c))
            else:
                rows[r].add(d); cols[c].add(d); boxes[r // 3 * 3 + c // 3].add(d)

    def options(r, c):
        taken = rows[r] | cols[c] | boxes[r // 3 * 3 + c // 3]
        return [d for d in "123456789" if d not in taken]

    def search():
        if not empty:
            return True
        # most constrained cell first: fewest legal digits
        k = min(range(len(empty)), key=lambda i: len(options(*empty[i])))
        r, c = empty[k]
        empty[k] = empty[-1]
        empty.pop()
        b = r // 3 * 3 + c // 3
        for d in options(r, c):
            board[r][c] = d
            rows[r].add(d); cols[c].add(d); boxes[b].add(d)
            if search():
                return True
            rows[r].remove(d); cols[c].remove(d); boxes[b].remove(d)
        board[r][c] = "."
        empty.append((r, c))
        return False

    return search()
Python: sets per row, column and box; always branch on the most constrained empty cell.

The function returns True after filling the grid, or False with the grid back in its original state when no solution exists. Swapping the chosen cell with the last list entry before popping removes it in O(1); appending it again on failure restores the same set of empty cells, even if their order changes.

Bitmasks in C++

Each set of digits fits in a 10-bit integer, with bit d meaning digit d is present. The digits available for a cell are the bits missing from rowMask | colMask | boxMask, so the check is one OR and one AND. The C++ version below fills blanks in reading order to stay short; adding fewest-options ordering means counting the zero bits of the combined mask for each blank, which std::popcount (C++20) or __builtin_popcount on GCC and Clang can do.

#include <array>
#include <vector>

// Bit d (1..9) set in rowMask[r] means digit d is already used in row r.
struct SudokuSolver {
    std::array<int, 9> rowMask{}, colMask{}, boxMask{};
    std::vector<std::pair<int, int>> blanks;

    static int box(int r, int c) { return r / 3 * 3 + c / 3; }

    bool solve(std::vector<std::vector<char>>& board) {
        for (int r = 0; r < 9; ++r)
            for (int c = 0; c < 9; ++c) {
                if (board[r][c] == '.') { blanks.push_back({r, c}); continue; }
                int bit = 1 << (board[r][c] - '0');
                rowMask[r] |= bit; colMask[c] |= bit; boxMask[box(r, c)] |= bit;
            }
        return place(board, 0);
    }

    bool place(std::vector<std::vector<char>>& board, size_t k) {
        if (k == blanks.size()) return true;
        auto [r, c] = blanks[k];
        int taken = rowMask[r] | colMask[c] | boxMask[box(r, c)];
        for (int d = 1; d <= 9; ++d) {
            int bit = 1 << d;
            if (taken & bit) continue;
            board[r][c] = char('0' + d);
            rowMask[r] |= bit; colMask[c] |= bit; boxMask[box(r, c)] |= bit;
            if (place(board, k + 1)) return true;
            rowMask[r] &= ~bit; colMask[c] &= ~bit; boxMask[box(r, c)] &= ~bit;
        }
        board[r][c] = '.';
        return false;
    }
};
C++17: bitmask constraints, blanks filled in reading order, undo on failure.

Both versions trust the givens. If two givens already clash, for example two 5s in one row, the sets quietly absorb the duplicate and the solver may report False or fill around the clash. Validate the givens first if the interviewer says the input might be malformed.

Going further: propagation

Stronger solvers add constraint propagation: after each placement, fill every cell that now has a single option, and look for a digit that has only one possible place in a row, column or box. Exact cover with Dancing Links is another known technique. These are good to name if the interviewer asks how to make it faster, but the backtracking above is what they expect you to write.

Complexity summary

E empty cells; the grid is fixed at 9 by 9
ApproachTimeExtra space
Try every digit everywhere, check at the endO(9^E)O(E)
Backtracking, scan row, column and box per checkO(9^E) worst case, 27 reads per checkO(E) recursion
Backtracking with sets or bitmasksO(9^E) worst case, O(1) per checkO(E) recursion plus 27 small sets
Plus fewest-options-firstSame worst case, far fewer nodes in practiceSame
E empty cells; the grid is fixed at 9 by 9. Scroll sideways on a small screen.

Since the board is fixed, some people call every version O(1). That is technically true and not useful. Say the worst case is exponential in the number of blanks and that pruning is what makes real puzzles fast.

Edge cases to test

  • An already complete, valid grid: return immediately with no changes.
  • An empty grid: any valid full grid is a solution, and both versions found one quickly in our runs.
  • An unsolvable grid whose givens do not clash directly, such as a row holding 1 to 8 with a 9 elsewhere in the last cell's column: return False and leave the grid unchanged.
  • A puzzle with more than one solution: the solver returns one of them.
  • Givens that clash, if the input may be malformed: validate first.

Common mistakes

  • Computing the box index as r // 3 + c // 3, which maps several boxes onto the same number.
  • Forgetting to reset the cell to a dot after all digits fail, so a stale digit is left behind when the search backs out.
  • Undoing the board but not the three constraint sets, or the reverse.
  • Copying the board at every level, which is slow and makes the in-place requirement awkward.
  • Returning after the first digit fails instead of trying the remaining digits.

How to explain it out loud

Fictional example

Laying out state before searching
Candidate
I'll keep three arrays of nine sets, for rows, columns and boxes, so checking a digit is constant time. Box index is row over 3 times 3 plus column over 3.
Candidate
Then backtracking: pick an empty cell, try each digit none of its sets have, recurse, and undo the cell and all three sets if it fails.
Candidate
For the cell, I'll take the one with the fewest options. A forced cell gets filled right away and a cell with no options fails fast. If speed matters more, I'd switch the sets to bitmasks.

Backtracking where repeated values, not rules, cause the wasted work is Permutations II. For a search that also benefits from trying the most constrained item first, see Partition to K Equal Sum Subsets, which places the largest values early. Grid backtracking over letters instead of digits is Word Search.

Grid problems are easy to read from an image and hard to debug by staring. When you practice, Natively on Mac and Windows can read a board problem from a screenshot and write an approach and code, search order included, to compare with your own. Reviewing the transcript shows whether you described your state before writing code. Find out how AI assists with coding interview prep.

Questions people ask

How do you solve Sudoku with backtracking?

Track the digits used in each row, column and box. Pick an empty cell, try each digit none of its three sets contain, recurse, and undo the cell and the sets if the branch fails.

How do you speed up a Sudoku solver?

Fill the empty cell with the fewest legal digits first, and use bitmasks so each check is one bitwise operation. Constraint propagation and exact-cover methods go further.

What is the time complexity of a Sudoku solver?

Exponential in the number of blanks in the worst case, O(9^E). Because the board is fixed at 81 cells, some call it constant, but pruning is what makes real puzzles fast.

How do you compute the box index in Sudoku?

For row r and column c, the box is (r // 3) × 3 + c // 3, which numbers the nine boxes 0 to 8 left to right, top to bottom.

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