Skip to content
Problem 794 · LeetCode 794(opens in a new tab)

Valid Tic-Tac-Toe State

MediumArrays

A tic-tac-toe board is given as board: three strings of three characters, each 'X', 'O' or ' ' (an empty square). Return true if this exact position can come up during a real game, and false otherwise.

The rules: the first player places X and the second places O, taking turns, always on an empty square. The game stops as soon as one player has three marks in a row, column or diagonal, or when all nine squares are full. After that nobody moves.

Example 1

Input:  board = ["XXX", "OO ", "   "]
Output: true
Why:    X won on its third move, one ahead of O
2 more examples and the constraints

Example 2

Input:  board = ["XXX", "OO ", "O  "]
Output: false
Why:    O kept playing after X had already won

Example 3

Input:  board = [" O ", "   ", "   "]
Output: false
Why:    X always moves first

Constraints

  • board has 3 rows of 3 characters
  • Each character is 'X', 'O' or ' '

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Play out every gameO(states)
  2. Count and check the winnerO(1)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for one boardVerdict
Play out every gameO(states)
Works, but heavy
Count and check the winnerO(1)
Best; three rules

states = the 5,478 boards a real game can reach.

Edge cases to test

  • Empty board. No moves yet is a valid position: true.
  • O moved first. [" O ", " ", " "] has more O than X: false.
  • Both players have a line. Impossible: the game stopped after the first one.
  • Two lines for X. One final mark can finish two lines: ["XXX", "XOO", "XOO"] is true.
  • Full board with no winner. A draw like ["XOX", "XOO", "OXX"] is true.

Common mistakes

  • Checking only the counts and forgetting that play stops after a win.
  • Rejecting a board where one player has two lines.
  • Requiring x = o + 1 when O wins; O won on its own move, so x = o.

How to talk through it

  1. 1Clarify. Who moves first? Does the game stop right after a win?
  2. 2Give the brute force. Simulate every game from the empty board and check membership.
  3. 3Name the rules. Count difference 0 or 1, and the winner must be the last to move.
  4. 4Code the checks. Count, test the turn rule, then test each winner against the counts.
  5. 5Test out loud. Run the empty board, an O-first board and a board where X has two lines.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?