CMD Guide
HomeDSAMatrix

medium Valid Sudoku

Problem Statement

Determine if a 9x9 Sudoku board is valid. A valid Sudoku board will hold the following conditions:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. The 9 3x3 sub-boxes of the grid must also contain the digits 1-9 without repetition.

Note:

  1. The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
  2. You need to validate only filled cells.

Example 1:

Example 2:

Example 3:

Constraints:

Pattern cue: validate uniqueness under three partitions (row, column, 3×3 box). Box id = (r/3)*3 + (c/3). Only filled cells matter — this is not "is the puzzle solvable."

Try it yourself

Try solving this question here:

🎯 STRICT STANDOUT: Why / complexity derivation / pattern+when-not / edges / drills — Valid Sudoku medium

Why this exists (judgment layer)

Validate uniqueness under three partitions (row, col, box) in one pass. Box id (r//3)*3+(c//3) is the encoding interviewers expect. Not 'solve the puzzle'.

Worked example & complexity derivation

For each filled cell (r,c,val):
  keys: row r, col c, box (r//3)*3+(c//3)
  if val already in any of three sets → invalid
Example2: board[0][0]='8' and board[3][0]='8' → same column 0 → false
  (rows each have one 8; row rule alone would pass)
One pass 81 cells; 3 sets of at most 9 → O(1) time for fixed 9×9, O(1) space
General n²×n² sudoku: O(n²) cells, O(n²) space

Pattern transfer & when-NOT

Pattern: MULTI-PARTITION UNIQUENESS with hash sets (or bitmasks). When-NOT: full solve → backtracking; count solutions → search; only check one constraint class. Empty '.' ignored. Partially filled boards can be valid yet unsolvable — out of scope.

Edge cases (hand-run)

All '.' → true. Single filled cell → true. Duplicate in one box only (same 3×3, different rows/cols) → false. Example3: column '5' twice.

Hostile-panel drills (defend the decision)

Q1. Box index for (r=5,c=7)?
Model answer: (5//3)*3+(7//3)=1*3+2=5 (0..8 boxes).

Q2. Why Example2 is false while rows look fine?
Model answer: Column 0 has two '8's at rows 0 and 3 — column constraint fails.

Q3. Bitmask alternative?
Model answer: Nine ints for rows/cols/boxes; bit val set if digit used — O(1) space tighter, same pass.

✅ Solution Valid Sudoku

Problem Statement

Determine if a 9x9 Sudoku board is valid. A valid Sudoku board will hold the following conditions:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. The 9 3x3 sub-boxes of the grid must also contain the digits 1-9 without repetition.

Note:

  1. The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
  2. You need to validate only filled cells.

Example 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 Output: true
  • Justification: This Sudoku board is valid as it adheres to the rules of no repetition in each row, each column, and each 3x3 sub-box.

Example 2:

  • Input:
    [["8","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 Output: false
  • Justification: Column 0 contains '8' in both row 0 and row 3, so the same digit repeats in one column and the board is invalid. (Each of those rows has only one '8'; the row constraint alone would pass.)

Example 3:

  • Input:
    [[".",".","4",".",".",".","6","3","."]
    ,[".",".",".",".",".",".",".",".","."]
    ,["5",".",".",".",".",".",".","9","."]
    ,[".",".",".","5","6",".",".",".","."]
    ,["4",".","3",".",".",".",".",".","1"]
    ,[".",".",".","7",".",".",".",".","."]
    ,[".",".",".","5",".",".",".",".","."]
    ,[".",".",".",".",".",".",".",".","."]
    ,[".",".",".",".",".",".",".",".","."]]
    
  • Expected Output: false
  • Justification: The fourth column contains the number '5' two times, violating the Sudoku rules.

Constraints:

  • board.length == 9
  • board[i].length == 9
  • board[i][j] is a digit 1-9 or '.'.

Pattern

Constraint encoding on a fixed board. Recognition: validate uniqueness under three partitions (row, column, 3×3 box). Map each filled cell to three keys and reject on any duplicate insert. Box index formula: box = (r/3)*3 + (c/3) for 0-based rows/cols on a 9×9 board — integer division groups the nine blocks into ids 0..8. Empty cells ('.') are ignored; validity is only about filled digits, not solvability.

Complexity: 81 cells, O(1) set ops each → O(1) time/space for fixed 9×9 (or O(n²) if generalized to n²×n²).

Solution

  • Initialization:
    • Create three hash sets for rows, columns, and boxes to keep track of the seen numbers.
  • Iteration:
    • Iterate through each cell in the 9x9 board.
      • If the cell is not empty:
        • Formulate keys for the row, column, and box that include the current number and its position.
        • Check the corresponding sets for these keys.
          • If any key already exists in the sets, return false.
          • Otherwise, add the keys to the respective sets.
  • Final Check:
    • If the iteration completes without finding any repetition, return true.

This approach works because it checks all the necessary conditions for a valid Sudoku by keeping track of the numbers in each row, column, and box using hash sets. The use of hash sets allows for efficient lookups to ensure no numbers are repeated in any row, column, or box.

Algorithm Walkthrough

Consider Example 2 from above:

  • Initialize three empty hash sets for rows, columns, and boxes.
  • Start iterating through each cell in the board.
    • For the first cell, which contains '8':
      • Formulate keys: row0(8), col0(8), and box0(8).
      • Since these keys are not in the sets, add them.
    • Continue this for other cells.
    • Upon reaching the first cell of the fourth row, which also contains '8':
      • Formulate keys: row3(8), col0(8), and box3(8) — box index is (i/3)*3 + j/3 = (3/3)*3 + 0 = 3.
      • The key col0(8) already exists in the column set, so return false.

Code

java
import java.util.HashSet;

public class Solution {

  public boolean isValidSudoku(char[][] board) {
    // Initialize sets to keep track of the numbers in each row, column, and box.
    HashSet<String> rows = new HashSet<>();
    HashSet<String> columns = new HashSet<>();
    HashSet<String> boxes = new HashSet<>();

    // Iterate through each cell in the 9x9 board.
    for (int i = 0; i < 9; i++) {
      for (int j = 0; j < 9; j++) {
        char num = board[i][j];
        if (num != '.') {
          // Formulate keys for the row, column, and box.
          String rowKey = "row" + i + "(" + num + ")";
          String colKey = "col" + j + "(" + num + ")";
          String boxKey = "box" + ((i / 3) * 3 + j / 3) + "(" + num + ")";
          // Check the corresponding sets for these keys.
          if (!rows.add(rowKey) || !columns.add(colKey) || !boxes.add(boxKey)) {
            return false;
          }
        }
      }
    }
    return true;
  }

  public static void main(String[] args) {
    Solution sol = new Solution();
    // Test the algorithm with three example inputs.
    char[][] board1 = {
      { '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' },
    };
    System.out.println(sol.isValidSudoku(board1)); // Output: true
  }
}

Complexity Analysis

  • Time Complexity: O(1) or O(81), as we only iterate through the 9x9 board once.
  • Space Complexity: O(1) or O(81), as the maximum size of our sets is 81.

🎯 STRICT STANDOUT: Why / worked+complexity / pattern+when-not / edge / drills — Solution Valid Sudoku

Why this concept exists (judgment layer)

Valid Sudoku is constraint encoding: three partitions (row, col, box) with uniqueness. box=(r//3)*3+(c//3) is the formula interviewers expect; validity ≠ solvability — only filled cells.

Worked example with complexity derivation

Example2: board almost like valid Ex1 but board[0][0]='8' and board[3][0]='8'.
Keys: row0(8), col0(8), box0(8) inserted at (0,0).
At (3,0): row3(8) new; col0(8) DUPLICATE → false. Rows alone would pass; column catches it.
box index for (3,0): (3//3)*3+(0//3)=3.
81 cells, O(1) set ops → O(1) for fixed 9×9 (O(n²) if generalized).
'.' skipped always.

Pattern + when-NOT / named alternative

PATTERN: three-key uniqueness scan; ignore empties; not a solver. WHEN NOT: need a completed solution → backtracking fill. bitmasks 9 ints instead of string sets — same idea faster constants. Do not early-exit only on rows — cols/boxes independent.

Edge case / failure mode

Edges: empty board all '.' → true; single digit; duplicate only in box not row/col. Failure: wrong box formula (r/3 + c/3); validating solvability.

Hostile-panel drills (defend the decision)

Q1. Give box id for cell (5,7).
Model answer: (5//3)*3+(7//3)=3+2=5.

Q2. Why Ex2 is false while rows look fine.
Model answer: Two '8's in column 0 (rows 0 and 3); row constraint alone does not see it.

Q3. Validity vs solution.
Model answer: Valid = no conflicts in filled cells; may still be unsolvable or incomplete.

🧩 Pattern · Matrix

Recognize it: Grid traversal / rotation / in-place marking → index arithmetic, or DFS/BFS over cells.

▶ Visualize this problem (step it, predict each fork)
⛶ Open this problem debugger in explore mode
🤖 Don't fully get this? Learn it with Claude

Stuck on Valid Sudoku? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Valid Sudoku** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Valid Sudoku** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Valid Sudoku**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Valid Sudoku**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes