call(back)
Algorithms & Data StructuresmediumSign in to star problems

Valid Tic-Tac-Toe State

An n × n tic-tac-toe board is given as n strings of X, O and spaces. X moves first, players alternate, and the game stops as soon as someone has n in a row, column or diagonal. Return whether the board could have been reached by a real game.

validTicTacToe(["XOX", " X ", "   "])  ->  false     // X moved twice in a row
validTicTacToe(["XOX", "O O", "XOX"])  ->  true
validTicTacToe(["XXX", "   ", "OOO"])  ->  false     // both cannot have won

Hints

Hint 1

Count X and O: X equals O or leads by exactly one, always.

Hint 2

If X has a line, X must lead by one (X made the last move); if O has a line, the counts must be equal. Both having a line is impossible, because the game stopped at the first.

Asked at