36. Valid Sudoku

Method 1 - use string

use string, to store

row, col, box's used value in set

simple way, but it's so slow... 12ms

/*
    time complexity: O(1), space complexity: O(1)
*/
class Solution {
    public boolean isValidSudoku(char[][] board) {
        Set<String> used = new HashSet<>();
        
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char num = board[i][j];
                if (num != '.') {
                     if (!used.add(num + "row" + i) ||
                         !used.add(num + "col" + j) ||
                         !used.add(num + "box" + i/3 + "-" + j/3)) {
                         return false;
                     }
                }
            }
        }
        return true;
    }
}

Method 2 - use 3 set

2ms

the key is

Method 3 - use bitwise operator

Last updated

Was this helpful?