Data Structures & Algorithms Hash Maps & Sets
💡
Exercise 33

Valid Sudoku 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Determine if a 9×9 Sudoku board is valid. Only the filled cells need to be validated according to these rules:

  • Each row must contain digits 1-9 without repetition
  • Each column must contain digits 1-9 without repetition
  • Each of the nine 3×3 sub-boxes must contain digits 1-9 without repetition

Use three sets of hash sets — one for rows, columns, and boxes. For each filled cell, check all three sets.

The 3×3 box index can be computed as (row // 3, col // 3).

📋 Instructions
For simplicity, validate this smaller example: Check if the row `[5, 3, '.', '.', 7, '.', '.', '.', '.']` has no duplicate digits. Print `True` if there are no duplicate digits (ignoring '.'), `False` otherwise. Then check `[5, 3, '.', '.', 5, '.', '.', '.', '.']` — this has duplicate 5s. Print both results.
For each row, create a set. Iterate through each element, skip '.', and check if the number is already in the set. If yes, it's invalid.
🧪 Test Cases
Input
is_valid_row([5, 3, '.', '.', 7, '.', '.', '.', '.'])
Expected
True
Boolean check
Input
is_valid_row([5, 3, '.', '.', 5, '.', '.', '.', '.'])
Expected
False
Boolean check
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.