LeetCode 36: Valid Sudoku Solution
Master LeetCode problem 36 (Valid Sudoku), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
36. Valid Sudoku
Problem Explanation
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:
- Initialize three sets for rows, columns, and sub-boxes.
- Iterate through each cell in the board.
- Check if the current digit is a duplicate in the corresponding row, column, or sub-box.
- If it is not a duplicate, add it to the corresponding set.
- If a duplicate is found, return false.
- 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.
Solution Code
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;
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 36 (Valid Sudoku)?
This page provides optimized solutions for LeetCode problem 36 (Valid Sudoku) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 36 (Valid Sudoku)?
The time complexity for LeetCode 36 (Valid Sudoku) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 36 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 36 in Java, C++, or Python.