Problem Description
Two players (A and B) play Tic Tac Toe on a 3x3 grid. Player A always plays first with 'X' and player B with 'O'. Given an array of moves where each move indicates the cell played, determine the outcome of the game: return "A" or "B" if a player wins, "Draw" if all cells are filled with no winner, or "Pending" if the game is still ongoing.
Key Insights
- Use board simulation by tracking rows, columns, and both diagonals.
- Represent moves with a numeric value (e.g., +1 for A, -1 for B) to check winning conditions easily.
- A win occurs when the absolute value of any row, column, or diagonal sum reaches 3.
- The moves array directly guides the simulation; each move’s index determines the player.
Space and Time Complexity
Time Complexity: O(1) (since the board size and maximum moves are fixed at 3x3 grid with at most 9 moves)
Space Complexity: O(1) (only constant extra space is used for counters)
Solution
We simulate each move and update counts for the affected row, column, and possibly the two diagonals:
- Initialize counters for rows, columns, and the two diagonals.
- For each move, determine the current player using the move index (even for A, odd for B). Assign +1 for A and -1 for B.
- Update the corresponding row and column counters.
- Check if the move is on the main diagonal (row == col) or anti-diagonal (row + col == 2) and update counts accordingly.
- After each update, check if the absolute value of any counter equals 3. If so, declare the respective winner.
- If all moves are completed without any player winning, return "Draw" if the board is full, or "Pending" otherwise.