DEV Community

Debesh P.
Debesh P.

Posted on

36. Valid Sudoku | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/valid-sudoku/


Detailed Step-by-Step Explanation

Solution 1: https://leetcode.com/problems/valid-sudoku/solutions/7463671/smartest-way-to-solve-most-optimal-uniqu-b8z4
Solution 2: https://leetcode.com/problems/valid-sudoku/solutions/7463665/most-optimal-solution-beats-200-n-hashse-bukb


leetcode 36


Solution 1

class Solution {
    public boolean isValidSudoku(char[][] board) {

        Set<String> set = new HashSet<>();

        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {

                char current = board[i][j];
                if (current == '.') continue;

                String rowKey = current + "_in_row_" + i;
                String colKey = current + "_in_column_" + j;
                String boxKey = current + "_in_box_" + (i / 3) + "_" + (j / 3);

                if (set.contains(rowKey) || set.contains(colKey) || set.contains(boxKey)) {
                    return false;
                }

                set.add(rowKey);
                set.add(colKey);
                set.add(boxKey);
            }
        }

        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Solution 2

class Solution {
    public boolean isValidSudoku(char[][] board) {

        boolean[][] rows = new boolean[9][9];
        boolean[][] cols = new boolean[9][9];
        boolean[][] boxes = new boolean[9][9];

        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (board[i][j] == '.') continue;

                int num = board[i][j] - '1';
                int boxIndex = (i / 3) * 3 + (j / 3);

                if (rows[i][num] || cols[j][num] || boxes[boxIndex][num]) {
                    return false;
                }

                rows[i][num] = true;
                cols[j][num] = true;
                boxes[boxIndex][num] = true;
            }
        }
        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)