- 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
- 53 lines of Java from the credited upstream file 348.java.
- The implementation visibly relies on sequence storage.
- 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 public TicTacToe(int n) {3 this.n = n;4 rows = new int[n];5 cols = new int[n];6 }7 8 /**9 * Player {player} makes a move at ({row}, {col}).10 *11 * @param row The row of the board.12 * @param col The column of the board.13 * @param player The player, can be either 1 or 2.14 * @return The current winning condition, can be either:15 * 0: No one wins.16 * 1: Player 1 wins.17 * 2: Player 2 wins.18 */19 public int move(int row, int col, int player) {20 final int toAdd = player == 1 ? 1 : -1;21 final int target = player == 1 ? n : -n;22 23 if (row == col) {24 diag += toAdd;25 if (diag == target)26 return player;27 }28 29 if (row + col == n - 1) {30 antiDiag += toAdd;31 if (antiDiag == target)32 return player;33 }34 35 rows[row] += toAdd;36 if (rows[row] == target)37 return player;38 39 cols[col] += toAdd;40 if (cols[col] == target)41 return player;42 43 return 0;44 }45 46 private final int n;47 48 private int[] rows;49 private int[] cols;50 private int diag = 0;51 private int antiDiag = 0;52}53