iq.lab
Python starts when a code cell comes near or you run one
mediumHash maps and sets target 25 min

Valid sudoku

A sudoku board is 9 by 9 cells, split into nine boxes of 3 by 3: rows 0 to 2, 3 to 5 and 6 to 8, crossed with the same three groups of columns. You get the board as a list of 9 rows, each a list of 9 one-character strings: a digit from "1" to "9", or "." for an empty cell.

Return True if no digit appears twice in the same row, the same column or the same box, and False otherwise. Empty cells never break a rule. You do not need to decide whether the board can be finished: a board can pass this check and still have no solution.

Example 1
Inputboard = [ [".", ".", ".", "5", ".", ".", "6", "7", "."], ["5", ".", ".", "7", ".", "6", ".", ".", "."], [".", ".", "1", ".", ".", ".", ".", "5", "."], [".", ".", ".", "4", ".", ".", "9", ".", "3"], [".", ".", "3", ".", ".", ".", "8", "4", "."], [".", ".", ".", ".", ".", "9", ".", "6", "."], [".", ".", "2", "8", "6", "7", "3", ".", "."], [".", ".", ".", ".", ".", ".", "5", ".", "2"], [".", ".", ".", ".", ".", "5", ".", ".", "."], ]OutputTrue

Each of the 24 filled digits is the only copy of itself in its row, its column and its box.

Example 2
Inputthe board from example 1, with board[0][1] = "1"OutputFalse

Row 0 and column 1 have no other 1, but the top-left box already has a 1 at row 2, column 2.

Example 3
Inputthe board from example 1, with board[8][6] = "9"OutputFalse

Column 6 already has a 9 at row 3.

Constraints
  • len(board) == 9 and len(board[r]) == 9 for every row r

  • Each cell is a digit from "1" to "9", or "."

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.