- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 44 lines of Python from the credited upstream file 348.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class TicTacToe:2 def __init__(self, n: int):3 self.n = n4 5 self.rows = [0] * n6 self.cols = [0] * n7 self.diag = 08 self.antiDiag = 09 10 """ Player {player} makes a move at ({row}, {col}).11 12 @param row The row of the board.13 @param col The column of the board.14 @param player The player, can be either 1 or 2.15 @return The current winning condition, can be either:16 0: No one wins.17 1: Player 1 wins.18 2: Player 2 wins.19 """20 21 def move(self, row: int, col: int, player: int) -> int:22 toAdd = 1 if player == 1 else -123 target = self.n if player == 1 else -self.n24 25 if row == col:26 self.diag += toAdd27 if self.diag == target:28 return player29 30 if row + col == self.n - 1:31 self.antiDiag += toAdd32 if self.antiDiag == target:33 return player34 35 self.rows[row] += toAdd36 if self.rows[row] == target:37 return player38 39 self.cols[col] += toAdd40 if self.cols[col] == target:41 return player42 43 return 044