DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 36. Valid Sudoku

Javascript Code

/**
 * @param {character[][]} board
 * @return {boolean}
 */


const checkInRow = (i, j, board) => {
    let seen = new Set();
    for (let col = 0; col < 9; col++) {
        let num = board[i][col];
        if (num !== ".") {
            if (seen.has(num)) return false;
            seen.add(num);
        }
    }
    return true
}

const checkInColumn = (i, j, board) => {
    let seen = new Set();
    for (let row = 0; row < 9; row++) {
        let num = board[row][j];
        if (num !== ".") {

            if (seen.has(num)) return false;
            seen.add(num);
        }
    }
    return true
}


const checkInSquare = (i, j, board) => {
    let seen = new Set();

    let startRow = Math.floor(i / 3) * 3;
    let startCol = Math.floor(j / 3) * 3;

    for (let row = startRow; row < startRow + 3; row++) {
        for (let col = startCol; col < startCol + 3; col++) {
            let num = board[row][col];

            if (num !== ".") {
                if (seen.has(num)) return false;
                seen.add(num);
            }
        }
    }
    return true
}

var isValidSudoku = function (board) {

    for (let i = 0; i < 9; i++) {

        for (let j = 0; j < 9; j++) {

            if (board[i][j] !== ".") {
                if (!(checkInRow(i, j, board) && checkInColumn(i, j, board) && checkInSquare(i, j, board))) return false;
            }
        }
    }

    return true;
};
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay