Valid Sudoku

Problem Information

Solution

The problem asks you to iterate the board the smartest possible way that you can. To be able to check it in one pass, you need to calculate a square or box index.

class Solution {
    public boolean isValidSudoku(char[][] board) {
        int boardSize = board.length;
        var columns = new ArrayList<HashSet<Character>>(boardSize);
        var rows = new ArrayList<HashSet<Character>>(boardSize);
        var squares = new HashMap<String, HashSet<Character>>();

        for (int i = 0; i < boardSize; i++) {
            columns.add(i, new HashSet<Character>());
            rows.add(i, new HashSet<Character>());
        }

        for (int r = 0; r < board.length; r++) {
            for (int c = 0; c < board.length; c++) {
                var num = board[r][c];
                if (num != '.') {
                    var columnSet = columns.get(c);
                    var rowSet = rows.get(r);

                    var squareKey = r/3 + "," + c/3;
                    squares.putIfAbsent(squareKey, new HashSet<Character>());
                    var squareSet = squares.get(squareKey);

                    if (columnSet.contains(num))
                        return false;
                    else
                        columnSet.add(num);

                    if (rowSet.contains(num))
                        return false;
                    else
                        rowSet.add(num);

                    if (squareSet.contains(num))
                        return false;
                    else
                        squareSet.add(num);

                }
            }
        }

        return true;
    }
}