AlgoMaster Logo

Valid Sudoku

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The Brute Force approach involves checking all rows, columns, and sub-grids (3x3) to ensure they contain unique numbers. This is straightforward but can be inefficient due to repeated checks.

Steps:

  1. Check each row to make sure there are no repeated numbers.
  2. Check each column and ensure no duplicates.
  3. Check each 3x3 sub-grid.

Code:

2. Optimized Approach Using HashSet

Intuition:

To optimize, use a HashSet for keeping track of seen numbers efficiently. We iterate once through the board, and at each step, we ensure that no number appears twice in its row, column or sub-grid.

Steps:

  1. A single loop performs checks using HashSet for:
    • Rows
    • Columns
    • 3x3 sub-grids
  2. For each filled cell, create unique keys for HashSets.

Code: