Taro Logo

Sudoku Solver

Hard
Asked by:
Amazon
Google
Snap
Meta
882 views
Topics:
ArraysRecursion

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

  1. Each of the digits 1-9 must occur exactly once in each row.
  2. Each of the digits 1-9 must occur exactly once in each column.
  3. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

The '.' character indicates empty cells.

Example 1:

Input: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
Output: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
Explanation: The input board is shown above and the only valid solution is shown below:


Constraints:

  • board.length == 9
  • board[i].length == 9
  • board[i][j] is a digit or '.'.
  • It is guaranteed that the input board has only one solution.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Is the input board guaranteed to be valid and solvable, or do I need to handle invalid or unsolvable initial configurations?
  2. If there are multiple valid solutions to the Sudoku puzzle, does the interviewer expect a specific one, or will any valid completed board be accepted?
  3. How are empty cells represented in the 2D board? Can I assume they are represented by the character '.' or the integer 0?
  4. What is the exact data type of the grid elements (e.g., characters from '1'-9 and '.', or integers from 0 to 9)?
  5. Should the board be modified strictly in-place, or is returning a new 2D array allowed if necessary?

Brute Force Solution

Approach

Imagine you have a Sudoku puzzle with several empty spots waiting to be filled with numbers. The brute force approach involves trying every single possible number in every empty spot until you find a combination that follows all the puzzle rules.

Here's how the algorithm would work step-by-step:

  1. Scan the puzzle to find the first empty spot.
  2. Try placing the number one into that empty spot.
  3. Check if this placement breaks any Sudoku rules, such as having the same number appear twice in the same row, column, or smaller box.
  4. If the number breaks a rule, erase it and try the number two instead.
  5. If the number is allowed, move on to the next empty spot and repeat the process of trying numbers from one onwards.
  6. If you reach a spot where no numbers can be legally placed, go back to the previous spot and change its number to the next option.
  7. Continue moving forward and backward, trying all combinations, until every single spot is successfully filled according to the rules.

Code Implementation

class Solution:
    def solveSudoku(self, board: list[list[str]]) -> None:
        def is_valid_placement(current_row, current_column, current_digit):
            string_digit = str(current_digit)
            for row_index in range(9):
                if board[row_index][current_column] == string_digit:
                    return False
                if board[current_row][row_index] == string_digit:
                    return False
                box_row = 3 * (current_row // 3) + row_index // 3
                box_col = 3 * (current_column // 3) + row_index % 3
                if board[box_row][box_col] == string_digit:
                    return False
            return True

        def backtrack_sudoku():
            # Scan the entire grid to locate the next unassigned cell for exploration
            for row_index in range(9):
                for column_index in range(9):
                    if board[row_index][column_index] == '.':
                        for candidate_digit in range(1, 10):
                            if is_valid_placement(row_index, column_index, candidate_digit):
                                board[row_index][column_index] = str(candidate_digit)
                                
                                # Recurse deeper to check if this valid branch leads to a complete solution
                                if backtrack_sudoku():
                                    return True
                                
                                # Backtrack by undoing the choice if the path leads to an invalid dead end
                                board[row_index][column_index] = '.'
                        return False
            return True

        backtrack_sudoku()

Big(O) Analysis

Time Complexity
O(9^(n^2)) – For a standard Sudoku board, the input size n represents the 9x9 grid containing up to 81 empty cells. In the worst-case scenario, an empty cell can have up to 9 possible digit choices (1 through 9), and each choice triggers a recursive step to evaluate the next empty spot. Since there are up to n^2 empty cells in total, the algorithm explores a decision tree with a branching factor of 9 up to a depth of n^2. This exhaustive exploration results in approximately 9^(n^2) recursive operations, which represents the upper-bound time complexity for solving an empty Sudoku puzzle.
Space Complexity
O(1) – The space complexity is determined by the maximum depth of the recursion stack when exploring empty spots and the constant extra space needed to track rule validations. Since a standard Sudoku board has a fixed size of 9 by 9 cells, the maximum number of recursive calls will never exceed 81, regardless of how many empty spots exist. Because the board dimensions are completely constant and do not scale with an arbitrary input size N, no dynamic or growing data structures are allocated. Therefore, the auxiliary space complexity remains constant at O(1) beyond the input board itself.

Optimal Solution

Approach

The optimal strategy to solve the puzzle is a method of careful trial and error combined with logical deduction. Instead of randomly guessing numbers everywhere, we search for the next empty space, try a valid number, and move forward, stepping back to change our choice only if we hit a dead end.

Here's how the algorithm would work step-by-step:

  1. Scan the board to find the next available empty spot that needs a number.
  2. Figure out which numbers are already present in the same row, the same column, and the smaller local box containing that empty spot.
  3. Choose a number that is not already used in that row, column, or local box.
  4. Place that number into the empty spot and temporarily assume it is correct.
  5. Move on to the next empty spot and repeat the process of finding valid numbers.
  6. If you reach a point where no valid numbers can be placed in a spot, recognize that an earlier choice was wrong, erase the recent entries, and try a different number in the previous spot.
  7. Continue this process of moving forward and backtracking until every spot on the board is successfully filled.

Code Implementation

class Solution:
    def solveSudoku(self, board: list[list[str]]) -> None:
        def is_valid_placement(current_board, row_index, col_index, candidate_char):
            box_start_row = 3 * (row_index // 3)
            box_start_col = 3 * (col_index // 3)
            for iterator in range(9):
                if current_board[row_index][iterator] == candidate_char:
                    return False
                if current_board[iterator][col_index] == candidate_char:
                    return False
                row_offset = box_start_row + (iterator // 3)
                col_offset = box_start_col + (iterator % 3)
                if current_board[row_offset][col_offset] == candidate_char:
                    return False
            return True

        def backtrack_solve(current_board):
            # Scan the board to find the next available empty spot that needs a number.

            for row_index in range(9):
                for col_index in range(9):
                    if current_board[row_index][col_index] == '.':
                        for candidate_digit in '123456789':
                            if is_valid_placement(current_board, row_index, col_index, candidate_digit):
                                current_board[row_index][col_index] = candidate_digit
                                # Assume current placement is correct and proceed to fill subsequent spots.

                                if backtrack_solve(current_board):
                                    return True
                                current_board[row_index][col_index] = '.'
                        # Backtrack if no valid number works here, allowing previous choices to change.

                        return False
            return True

        backtrack_solve(board)

Big(O) Analysis

Time Complexity
O(9^(n^2)) – For a standard 9x9 Sudoku board, the input size n is 9, meaning there are n squared or 81 total cells to fill. At each empty cell, the algorithm may potentially try up to 9 different valid numbers, leading to a branching factor of up to 9 for each of the 81 cells in the worst-case scenario. This recursive trial and error explores a search space of up to 9 to the power of n squared possible board configurations. As the recursion steps forward and backtracks upon hitting dead ends, the total operations approximate 9 to the power of 81 combinations, which simplifies to the Big O notation of O(9 to the power of n squared).
Space Complexity
O(1) – Since the Sudoku board has a fixed size of 9 by 9 cells, the number of empty spots and the maximum recursion depth are bounded by a constant maximum of 81 levels. The algorithm only uses a few scalar variables to track row, column, and digit choices, meaning no auxiliary data structures grow with the input. Therefore, the extra memory required remains constant regardless of the configuration of the puzzle.

Edge Cases

Null or empty board input
How to Handle:
Check for null or incorrect dimensions at the start and return immediately without crashing
Board with no valid solution
How to Handle:
The backtracking algorithm will exhaust all possibilities and return false, leaving the board in a valid state or signaling failure
Board with multiple valid solutions
How to Handle:
The recursive search will return true upon finding the first valid completion, effectively stopping and returning that solution
Board already completely solved
How to Handle:
The algorithm will find no empty cells and immediately return true without making any unnecessary changes
Invalid initial board with pre-existing rule violations
How to Handle:
Validation checks prior to placement will instantly reject conflicting numbers and trigger backtracking or failure
Deep recursion stack overflow on complex puzzles
How to Handle:
Since the board size is fixed at 9x9, the maximum recursion depth is strictly bounded by 81, preventing stack overflow