/36. Valid Sudoku

36. Valid Sudoku

Medium
Arrays64.2% acceptance

Given a 9x9 matrix grid, where each element is a string representing a digit 1-9 or the character ., determine if the filled cells form a valid Sudoku configuration. A configuration is valid if: (1) Each row contains no repeated digits (excluding .); (2) Each column contains no repeated digits (excluding .); (3) Each of the nine 3x3 sub-grids contains no repeated digits (excluding .). Only filled cells need to be checked. Return True if valid, otherwise False.

Example 1

Input: [[1,2,3,4,5,6,7,8,9],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.]]

Output: True

Explanation: Only the first row is filled and contains unique digits.

Example 2

Input: [[1,2,3,4,5,6,7,8,9],[1,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.]]

Output: False

Explanation: Digit 1 is repeated in the first column.

Example 3

Input: [[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.],[.,.,.,.,.,.,.,.,.]]

Output: True

Explanation: All cells are empty.

Constraints

  • grid has 9 rows
  • Each row in grid has 9 columns
  • Each element in grid is either a digit 1-9 or .
Python (current runtime)

Case 1

Input: [['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']]

Expected: True

Case 2

Input: [['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','8']]

Expected: False