Arrays and Hashing Hash map lookups

63. Valid Sudoku

Medium

You are given a Sudoku board as 9 strings, one per row from top to bottom. Each string has 9 characters. A character is 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.

The board is split into nine boxes of 3 × 3 cells. Rows 0–2, 3–5 and 6–8 meet columns 0–2, 3–5 and 6–8 to form them, so every cell belongs to exactly one box. A 3 × 3 square that crosses a box border is not a box.

Only the digits already on the board are checked. The board may have any number of empty cells, and it does not need to have a solution.

Example 1

328486545217175349184281614857514

Input: board = [".32...8..", "...486.5.", "4..5.2.17", "..1...7.5", "3.49....1", "...8....4", "2.8...16.", ".1..4857.", ".5..1.4.."]

Output: true

Explanation: Every row, column and box holds each digit at most once. Empty cells are not checked.

Example 2

83313792574276284519

Input: board = ["8.....3..", "..3..1...", "37..9...2", "...5...7.", "....4....", ".2...7...", "6...2..8.", "...4..5..", "..1.....9"]

Output: false

Explanation: Row 1 has a 3 in column 2, and row 2 has a 3 in column 0. They are in different rows and different columns, but both are in the top-left box, so that box holds the digit 3 twice.

Example 3

123456789

Input: board = ["12345678.", ".........", ".........", "........9", ".........", ".........", ".........", ".........", "........."]

Output: true

Explanation: No digit repeats, so the board is valid. It cannot be finished: the last cell of row 0 needs a 9, but column 8 already has one. That does not change the answer.

Check your understanding

Work out the answer for this input before you write any code.

board = ["1........", ".........", ".........", "....7....", ".........", "...7.....", ".........", ".........", "........2"]

Constraints

  • board.length = 9
  • board[i].length = 9
  • board[i][j] is one of '1' to '9', or '.'

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.