36. Valid Sudoku

ArrayHash TableMatrix

Explanation

To solve this problem, we need to validate if a given Sudoku board is valid according to the rules mentioned in the problem description. We can iterate through each row, each column, and each 3x3 sub-box to check for duplicates. We can use three sets to keep track of seen digits in rows, columns, and sub-boxes. If we encounter a digit that is already in the set, the board is invalid. If we finish iterating without finding any duplicates, the board is valid.

  • Algorithm:

    1. Initialize three sets for rows, columns, and sub-boxes.
    2. Iterate through each cell in the board.
    3. Check if the current digit is a duplicate in the corresponding row, column, or sub-box.
    4. If it is not a duplicate, add it to the corresponding set.
    5. If a duplicate is found, return false.
    6. If no duplicates are found, return true.
  • Time Complexity: O(1) since the board is always 9x9.

  • Space Complexity: O(1) since the sets will always have at most 9 unique elements.

class Solution {
    public boolean isValidSudoku(char[][] board) {
        Set<String> seen = new HashSet<>();
        
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char currentVal = board[i][j];
                if (currentVal != '.') {
                    if (!seen.add(currentVal + " in row " + i) ||
                        !seen.add(currentVal + " in column " + j) ||
                        !seen.add(currentVal + " in sub-box " + i/3 + "-" + j/3)) {
                        return false;
                    }
                }
            }
        }
        
        return true;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.