A readable Python solution

  • 29

    Apparently not the shortest solution but I think it's easy to follow the logic.

    def isValidSudoku(self, board):
        return (self.is_row_valid(board) and
                self.is_col_valid(board) and
    def is_row_valid(self, board):
        for row in board:
            if not self.is_unit_valid(row):
                return False
        return True
    def is_col_valid(self, board):
        for col in zip(*board):
            if not self.is_unit_valid(col):
                return False
        return True
    def is_square_valid(self, board):
        for i in (0, 3, 6):
            for j in (0, 3, 6):
                square = [board[x][y] for x in range(i, i + 3) for y in range(j, j + 3)]
                if not self.is_unit_valid(square):
                    return False
        return True
    def is_unit_valid(self, unit):
        unit = [i for i in unit if i != '.']
        return len(set(unit)) == len(unit)

  • 0

    I think this version is more acceptable in the interview. thanks.

  • 0

    Thanks for your solution! But what is the running time of the function "is_square_valid(self, board)"? It seems to have 4 for loops.

  • 0

    This is a way better answer in terms of readability

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.