← Back to Leo Academy Masterclass

Problem #36: Valid Sudoku

Medium Matrix

Intuition & Strategy Breakdown

Use hash sets or boolean arrays to validate each row, column, and 3x3 sub-grid. Iterate through the grid and ensure no digit from '1'-'9' appears twice in any valid section.

Python Solution

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        cols = [set() for _ in range(9)]
        rows = [set() for _ in range(9)]
        squares = [set() for _ in range(9)]

        for r in range(9):
            for c in range(9):
                if board[r][c] == ".":
                    continue
                if (board[r][c] in rows[r] or
                    board[r][c] in cols[c] or
                    board[r][c] in squares[(r // 3) * 3 + (c // 3)]):
                    return False
                
                cols[c].add(board[r][c])
                rows[r].add(board[r][c])
                squares[(r // 3) * 3 + (c // 3)].add(board[r][c])
        return True

Java Solution

class Solution {
    public boolean isValidSudoku(char[][] board) {
        Set seen = new HashSet<>();
        for (int i = 0; i < 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                char number = board[i][j];
                if (number != '.') {
                    if (!seen.add(number + " in row " + i) ||
                        !seen.add(number + " in column " + j) ||
                        !seen.add(number + " in block " + i / 3 + "-" + j / 3))
                        return false;
                }
            }
        }
        return true;
    }
}
Watch Interactive Video on Leo Academy Main App