> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Valid Tic-Tac-Toe State Python Solution

> Tested Python solution for LeetCode 794 with 24 pytest cases. Generate a practice environment with lcpy.

LeetCode 794, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Matrix](/catalog/topics/matrix). [View on LeetCode](https://leetcode.com/problems/valid-tic-tac-toe-state/description/).

Generate this problem as a practice environment: tested reference solution, 24 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 794   # by problem number
lcpy gen -s valid_tic_tac_toe_state   # by problem name
```

## Problem

Given a Tic-Tac-Toe board as a string array `board`, return `true` if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.

The board is a `3 x 3` array that consists of characters `' '`, `'X'`, and `'O'`. The `' '` character represents an empty square.

Here are the rules of Tic-Tac-Toe:

* Players take turns placing characters into empty squares `' '`.
* The first player always places `'X'` characters, while the second player always places `'O'` characters.
* `'X'` and `'O'` characters are always placed into empty squares, never filled ones.
* The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.
* The game also ends if all squares are non-empty.
* No more moves can be played if the game is over.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/05/15/tictactoe1-grid.jpg)

```
Input: board = ["O  ","   ","   "]
Output: false
Explanation: The first player always plays "X".
```

![Example 2](https://assets.leetcode.com/uploads/2021/05/15/tictactoe2-grid.jpg)

```
Input: board = ["XOX"," X ","   "]
Output: false
Explanation: Players take turns making moves.
```

![Example 3](https://assets.leetcode.com/uploads/2021/05/15/tictactoe4-grid.jpg)

```
Input: board = ["XOX","O O","XOX"]
Output: true
```

### Constraints

* board.length == 3
* board\[i].length == 3
* `board[i][j]` is either `'X'`, `'O'`, or `' '`.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/valid_tic_tac_toe_state/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/valid_tic_tac_toe_state/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(1) - the board is always 3 x 3
    # Space: O(1)

    def valid_tic_tac_toe(self, board: list[str]) -> bool:
        x_count = sum(row.count("X") for row in board)
        o_count = sum(row.count("O") for row in board)

        if o_count not in (x_count - 1, x_count):
            return False

        x_wins = self._wins(board, "X")
        o_wins = self._wins(board, "O")

        if x_wins and o_wins:
            return False
        if x_wins:
            return x_count == o_count + 1
        if o_wins:
            return x_count == o_count
        return True

    def _wins(self, board: list[str], player: str) -> bool:
        lines = [board[i] for i in range(3)]
        lines += ["".join(row[j] for row in board) for j in range(3)]
        lines.append("".join(board[i][i] for i in range(3)))
        lines.append("".join(board[i][2 - i] for i in range(3)))
        return any(line == player * 3 for line in lines)
```

## Complexity

| Time | Space |
| - | - |
| O(1) - the board is always 3 x 3 | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.