# Valid Sudoku

Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**:

1. Each row must contain the digits `1-9` without repetition.
2. Each column must contain the digits `1-9` without repetition.
3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition.

![](https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png)*Note: Empty cells consists of '.'(dot) character* &#x20;

### Approach1:

We first take note of the above specified properties of a Sudoku. Intuitively, we're thinking about using a Set here since we might have to implement some sort of solution that accounts for duplicates.&#x20;

The logic is as a follow, if we encode each element that we encounter with their corresponding row -> column -> 3x3 box, we would be able to later verify by using a Set whether they are unique.

For example:     (credit: [StefanPochmann](http://www.stefan-pochmann.info/))

* `'4' in row 7` is encoded as `"(4)7"`.
* `'4' in column 7` is encoded as `"7(4)"`.
* `'4' in the top-right block` is encoded as `"0(4)2"`.

Scream `false` if we ever fail to add something because it was already added (i.e., seen before).

* We iterate thorugh the matrix (board) and we store each non-empty cells values into a set along with their column. row, 3X3 information
* The set contains unique values, if the element is already found within the set, by virtue of the above prorperties, the Sudoke in question is not valid.

```python
class Solution(object):
    def isValidSudoku(self, board):
        seen = set()
        for i, row in enumerate(board):
            for j, e in enumerate(row):
                if e !='.':
                    if (i,e) in seen or (e,j) in seen or (i/3,j/3,e) in seen:
                        return False
                    seen.add((i,e))
                    seen.add((e,j))
                    seen.add((i/3,j/3,e))
        return True
```

**`Time: O(n2)                Space: O(distinct(k) k = elements`**

### Approach1: Java Version

```python
class Solution {
    public boolean isValidSudoku(char[][] board) {
        Set<String> set = new HashSet<>();
        
        for(int row = 0; row < board.length; row++){
            for(int col = 0; col < board[row].length; col++){
                char val = board[row][col];
                if(val != '.'){
                    if(!set.add(val + " in row " + row)
                    || !set.add(val + " in column " + col)
                    || !set.add(val + " in sub-box " + row/3 + " " + col/3)) return false;
                }
            }
        }
        return true;
    }
}
```

### Approach2: Coordinates

**`Time: O(n2)                Space: O(distinct(k) k = elements`**

A different approach we can use if by implementing a method  **`isValid`** which takes in coordinates and ensures that the elements within the coordinates are unique. This approach is very intuitive however it can be bit delicate as we have to make sure that the passed coordinates are accurates.&#x20;

*Note: We use ther modulo operator% for **3\*3**. Because % increments and resets back by staying within the box constraints.*

```python
class Solution {
    public boolean isValidSudoku(char[][] board) {
        
        for(int i = 0; i < board.length; i++){
            if(!isValid(board, i, i, 0, 8) || !isValid(board, 0, 8, i, i) || !isValid(board, i/3*3, i/3*3+2,i%3*3, i%3*3+2)) return false;
        }
        return true;
    }
    private boolean isValid(char[][]board, int x1, int x2, int y1, int y2){
        Set<Integer> set = new HashSet<>();
        
        for(int row = x1; row <= x2; row++){
            for(int col = y1; col <= y2; col++){
                if(board[row][col] != '.' && !set.add(board[row][col] - '0')) return false;
            }
        }
        return true;
    }
}
```

####


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kseb0.gitbook.io/whiteboard/arrays-and-strings/valid-sudoku.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
