Find Winner on a Tic Tac Toe Game (LeetCode 1275): Solution and Explanation

Easy
Array
Hash Table
Matrix
Simulation

Replay a list of tic-tac-toe moves where A moves first, and report "A" or "B" for the winner, "Draw" for a full board with no winner, or "Pending" if the game is not finished.

Intuition

A player wins when one of eight lines is all theirs: three rows, three columns and two diagonals. So the only thing worth tracking is how full each line is, and by whom.

Give A the value +1 and B the value -1, and keep one running sum per line. A line where both players have played can never sum to 3 or -3, because the marks cancel. A sum of +3 means three X marks; -3 means three O marks.

A move at (r, c) only touches row r, column c, the main diagonal when r == c and the anti-diagonal when r + c == 2. Those are the only counters that can change, so they are the only ones to check after the move.

If the moves run out without a winner, the board size decides the rest: nine moves means a Draw, fewer means the game is still Pending.

Approach: Signed line counters

  1. Create rows = [0,0,0], cols = [0,0,0], diag = 0, anti = 0.
  2. For each move i at (r, c), set p = 1 if i is even (A), otherwise p = -1 (B).
  3. Add p to rows[r] and cols[c]; add it to diag if r == c and to anti if r + c == 2.
  4. If any of rows[r], cols[c], diag, anti has absolute value 3, return "A" when p == 1, else "B".
  5. After the loop, return "Draw" if there were 9 moves, otherwise "Pending".

Step-by-step example

moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
  1. Move 1, A at (0,0): rows[0] = 1, cols[0] = 1, diag = 1. No counter is at 3.
  2. Move 2, B at (2,0): rows[2] = -1, cols[0] = 0 (A and B cancel), anti = -1.
  3. Move 3, A at (1,1): rows[1] = 1, cols[1] = 1, diag = 2, anti = 0. The center lies on both diagonals.
  4. Move 4, B at (2,1): rows[2] = -2, cols[1] = 0. B threatens row 2 but it is A's turn.
  5. Move 5, A at (2,2): diag becomes 3, so A owns the whole main diagonal. Return "A".

Code: Python, Java, C++

1class Solution:
2    def tictactoe(self, moves: List[List[int]]) -> str:
3        rows, cols = [0] * 3, [0] * 3
4        diag = anti = 0
5        for i, (r, c) in enumerate(moves):
6            p = 1 if i % 2 == 0 else -1
7            rows[r] += p
8            cols[c] += p
9            if r == c:
10                diag += p
11            if r + c == 2:
12                anti += p
13            if 3 in (abs(rows[r]), abs(cols[c]), abs(diag), abs(anti)):
14                return "A" if p == 1 else "B"
15        return "Draw" if len(moves) == 9 else "Pending"
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m)

Each of the m moves (at most 9) updates and checks at most four counters in constant time.

Space

O(1)

Only eight integer counters are kept, regardless of input.

Other approaches

Fill the board and scan all lines (time O(m + 9), space O(9))

Place every move on a 3 x 3 board, then check all eight lines for three equal marks. This is easy to read and still constant time on a 3 x 3 board, but it only checks the final board, which is fine here because the game stops at the first win.

Check only the last mover (time O(m), space O(m))

Only the player who made the last move can have won, so check whether that player's move set contains any of the eight winning triples. Neat, but it depends on the guarantee that the input stops at the first win.

Common mistakes

  • Getting the turn order wrong: A owns the even indices (0, 2, 4, ...), not the odd ones.
  • Forgetting that the center (1,1) lies on both diagonals, so it must update diag and anti.
  • Using r - c == 0 for the anti-diagonal; the anti-diagonal is r + c == 2 on a 3 x 3 board.
  • Returning "Draw" for any game without a winner; a game with fewer than 9 moves is "Pending".
  • Comparing counters to 3 only and missing B's wins at -3.

Frequently asked questions

Why can a counter only reach 3 or -3 when one player owns the whole line?

A line has three cells. Each X adds 1 and each O subtracts 1, so the sum's absolute value is 3 only if all three cells hold the same mark. Any mix of X and O gives a smaller absolute value.

Do I need to check all eight lines after each move?

No. A move at (r, c) changes at most four lines, so only those counters can newly reach 3. Checking all eight is also correct, just a bit more work.

How does this generalize to an n x n board?

Keep n row counters, n column counters and two diagonal counters, and test for absolute value n instead of 3. Each move stays O(1), which is the same idea used in Design Tic-Tac-Toe.