[
math
recursion
]
Leetcode 0794 Valid Tic-Tac-Toe State
Problem statement
https://leetcode.com/problems/valid-tic-tac-toe-state/
Solution
Let us evaluate several characteristic of our board: number of O
, number of X
, number of full lines with X
, which we call XXX
and also OOO
. Then board can be valid only in two cases:
- Number of
X
is one more than number ofO
, it means that last move was made by first: in this caseOOO
must be equal to zero andXXX
should be less or equal than2
(actually we do not need to check last condition) - Number of
X
is equal to number ofO
, it means, that last move was made be second: in this caseXXX
must be equal to zero andOOO
should be less or equal to1
(again no need to check it in fact)
Complexity
Overall time complexity is O(n^2)
, where n = 3
is size of our grid, space complexity is the same.
Code
class Solution:
def validTicTacToe(self, board):
line = "".join(board)
fin = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
XXX, OOO = 0, 0
X, O = line.count("X"), line.count("O")
for a,b,c in fin:
XXX += (line[a] + line[b] + line[c] == "XXX")
OOO += (line[a] + line[b] + line[c] == "OOO")
if X - O == 1 and XXX <= 2 and OOO == 0: return True
if X - O == 0 and OOO <= 1 and XXX == 0: return True
return False