Valid Sudoku

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: Empty cells consists of '.'(dot) character

Approach1:

We first take note of the above specified properties of a Sudoku. Intuitively, we're thinking about using a Set here since we might have to implement some sort of solution that accounts for duplicates.

The logic is as a follow, if we encode each element that we encounter with their corresponding row -> column -> 3x3 box, we would be able to later verify by using a Set whether they are unique.

For example: (credit: StefanPochmann)

  • '4' in row 7 is encoded as "(4)7".

  • '4' in column 7 is encoded as "7(4)".

  • '4' in the top-right block is encoded as "0(4)2".

Scream false if we ever fail to add something because it was already added (i.e., seen before).

  • We iterate thorugh the matrix (board) and we store each non-empty cells values into a set along with their column. row, 3X3 information

  • The set contains unique values, if the element is already found within the set, by virtue of the above prorperties, the Sudoke in question is not valid.

class Solution(object):
    def isValidSudoku(self, board):
        seen = set()
        for i, row in enumerate(board):
            for j, e in enumerate(row):
                if e !='.':
                    if (i,e) in seen or (e,j) in seen or (i/3,j/3,e) in seen:
                        return False
                    seen.add((i,e))
                    seen.add((e,j))
                    seen.add((i/3,j/3,e))
        return True

Time: O(n2) Space: O(distinct(k) k = elements

Approach1: Java Version

Approach2: Coordinates

Time: O(n2) Space: O(distinct(k) k = elements

A different approach we can use if by implementing a method isValid which takes in coordinates and ensures that the elements within the coordinates are unique. This approach is very intuitive however it can be bit delicate as we have to make sure that the passed coordinates are accurates.

Note: We use ther modulo operator% for 3*3. Because % increments and resets back by staying within the box constraints.

Last updated

Was this helpful?