Taro Logo

Valid Sudoku

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+26
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.4K views
Topics:
Arrays

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 according to the mentioned rules.

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: true

Example 2:

Input: board = 
[["8","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: false
Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.

Constraints:

  • board.length == 9
  • board[i].length == 9
  • board[i][j] is a digit 1-9 or '.'.

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. Are we guaranteed that the input is always a 9x9 2D array, or should I handle variable dimensions?
  2. How are empty or unfilled cells represented in the 2D array (e.g., '.', ' ', or '')?
  3. Should we validate that the input contains only valid characters (digits '1'-9' and the empty cell representation), or can we assume the input is well-formed otherwise?
  4. Does the problem require us to validate that the board is solvable, or are we strictly checking the validity of the current placement of filled cells?
  5. If the board contains invalid entries, should we return false immediately upon finding the first violation, or process the entire board?

Brute Force Solution

Approach

To check if a Sudoku board is valid using a brute force approach, you can systematically inspect every single row, column, and smaller region to ensure no numbers are repeated. This exhaustive checking guarantees that every rule of the game is respected across the entire board.

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

  1. Start by looking at the very first row of the board to make sure no number appears more than once.
  2. Next, check the second row, and continue this process until every single row has been inspected.
  3. After finishing the rows, move on to the columns, checking the first column for any repeated numbers.
  4. Continue checking every remaining column one by one until all of them are verified.
  5. Then, focus on the smaller square regions that make up the board, starting with the top left region.
  6. Check that small region to ensure it contains no duplicate numbers.
  7. Move through all the remaining regional squares one by one, checking each of them thoroughly.
  8. If all the rows, columns, and smaller regions pass their checks without any duplicates, conclude that the board is valid.

Code Implementation

def isValidSudoku(board):
    # We must check every row independently to ensure no numbers from one to nine repeat
    for row_index in range(9):
        seen_digits = set()
        for col_index in range(9):
            current_value = board[row_index][col_index]
            if current_value != ".":
                if current_value in seen_digits:
                    return False
                seen_digits.add(current_value)

    # We check each column separately since vertical duplicates violate sudoku rules
    for col_index in range(9):
        seen_digits = set()
        for row_index in range(9):
            current_value = board[row_index][col_index]
            if current_value != ".":
                if current_value in seen_digits:
                    return False
                seen_digits.add(current_value)

    # Each three by three subgrid must be validated to catch local duplicates
    for box_row in range(0, 9, 3):
        for box_col in range(0, 9, 3):
            seen_digits = set()
            for row_offset in range(3):
                for col_offset in range(3):
                    current_row = box_row + row_offset
                    current_col = box_col + col_offset
                    current_value = board[current_row][current_col]
                    if current_value != ".":
                        if current_value in seen_digits:
                            return False
                        seen_digits.add(current_value)

    return True

Big(O) Analysis

Time Complexity
O(1) – Since a standard Sudoku board is always fixed at a constant size of 9 by 9 cells, the number of operations required to inspect all rows, columns, and 3-by-3 sub-boxes never changes regardless of the input. The algorithm iterates through a constant 81 cells a fixed number of times to check for duplicates. Because the dimensions n are strictly constant rather than variable, the total operations remain bounded by a constant limit. Therefore, the time complexity simplifies to O(1).
Space Complexity
O(1) – To validate the Sudoku board, we use hash sets or tracking arrays to keep track of the numbers seen in each row, column, and 3-by-3 sub-grid. Since the board has a fixed size of 9-by-9 cells, these tracking structures store at most a constant number of elements, precisely 9 integers per row, column, and region. Therefore, the extra memory used by the algorithm does not grow with any variable input size N and remains completely constant. Ultimately, this constant auxiliary space simplifies to Big O notation as O(1).

Optimal Solution

Approach

To efficiently check if a Sudoku board is valid, we can inspect every single cell once while keeping track of the numbers we have already seen. By using three distinct mental checklists for every row, column, and smaller box, we can instantly spot if any number is repeated illegally.

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

  1. Imagine you are walking through the board and looking at every single filled-in spot one by one.
  2. Every time you see a number, check your personal memory log for the specific row you are currently in to ensure that number has not appeared there yet.
  3. Next, check your separate memory log for the specific column you are in to make sure the number is not duplicated vertically.
  4. Then, check your third memory log dedicated to that specific smaller sub-grid box to ensure the number is unique within its local neighborhood.
  5. If the number is completely new to all three of those specific memory logs, add it to them and move on to the next spot.
  6. If you ever find that a number is already recorded in any of those three memory logs, you immediately know the board breaks the rules and is invalid.
  7. If you successfully inspect every single filled spot on the board without triggering any duplicates, declare that the board is completely valid.

Code Implementation

def isValidSudoku(board):
    seen_elements_set = set()

    # We traverse every single cell in the 9x9 grid to inspect each number.
    for row_index in range(9):
        for col_index in range(9):
            current_element = board[row_index][col_index]

            if current_element == ".":
                continue

            box_index = (row_index // 3, col_index // 3)
            row_identifier = (row_index, current_element)
            col_identifier = (current_element, col_index)
            box_identifier = (box_index, current_element)

            # We check the three distinct memory logs to guarantee absolute uniqueness.
            if row_identifier in seen_elements_set or col_identifier in seen_elements_set or box_identifier in seen_elements_set:
                return False

            seen_elements_set.add(row_identifier)
            seen_elements_set.add(col_identifier)
            seen_elements_set.add(box_identifier)

    # Reaching this point guarantees the entire board contains no rule violations.
    return True

Big(O) Analysis

Time Complexity
O(1) – Since a Sudoku board always has a fixed size of 9 by 9 cells, the total number of cells to inspect is a constant 81. As we iterate through each of the n cells on the board, we perform constant-time lookup and insertion operations into our row, column, and box memory logs. Because the board dimensions never scale with a variable input size, the number of operations remains strictly bounded. Therefore, this total constant amount of work simplifies to an O(1) time complexity.
Space Complexity
O(1) – To track visited numbers, the algorithm utilizes memory logs corresponding to rows, columns, and sub-grids, but because a standard Sudoku board is strictly fixed at 9 by 9 cells, these data structures store at most 81 entries. Since the maximum number of filled spots and unique identifiers processed is bounded by a constant limit regardless of any larger input scale, the auxiliary space remains constant. As the board dimensions never scale beyond this fixed 9 by 9 grid, the extra memory used does not grow with N.

Edge Cases

Board contains only empty cells denoted by period characters
How to Handle:
The validation loop skips non-digit characters and immediately returns true for an entirely empty board
Board has identical digits appearing multiple times in the same row, column, or 3x3 sub-box
How to Handle:
The tracking sets detect the duplicate entry upon insertion and immediately return false
Input board contains invalid characters outside of digits 1 through 9 and period characters
How to Handle:
The validation logic ignores or fails on unexpected characters, so input sanitization or strict digit checks should be applied beforehand
Maximum-sized board filled completely with a valid Sudoku configuration
How to Handle:
The algorithm iterates through all 81 cells once in O(1) time and space complexity due to the fixed 9x9 dimensions
Board with invalid values localized strictly to the final 3x3 sub-box at the bottom right
How to Handle:
The single-pass traversal efficiently evaluates all rows, columns, and boxes, catching the error regardless of its position
Inputs with multiple duplicate values across different rows sharing the same column or sub-box
How to Handle:
String-formatted identifiers for rows, columns, and boxes ensure collisions are accurately tracked across distinct geometric regions
0/75 completed