Find Winner on a Tic Tac Toe Game (LeetCode 1275): Solution and Explanation
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
- Create
rows = [0,0,0],cols = [0,0,0],diag = 0,anti = 0. - For each move
iat(r, c), setp = 1ifiis even (A), otherwisep = -1(B). - Add
ptorows[r]andcols[c]; add it todiagifr == cand toantiifr + c == 2. - If any of
rows[r],cols[c],diag,antihas absolute value 3, return"A"whenp == 1, else"B". - 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]]
- Move 1, A at (0,0): rows[0] = 1, cols[0] = 1, diag = 1. No counter is at 3.
- Move 2, B at (2,0): rows[2] = -1, cols[0] = 0 (A and B cancel), anti = -1.
- Move 3, A at (1,1): rows[1] = 1, cols[1] = 1, diag = 2, anti = 0. The center lies on both diagonals.
- Move 4, B at (2,1): rows[2] = -2, cols[1] = 0. B threatens row 2 but it is A's turn.
- 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"1class Solution {
2 public String tictactoe(int[][] moves) {
3 int[] rows = new int[3], cols = new int[3];
4 int diag = 0, anti = 0;
5 for (int i = 0; i < moves.length; i++) {
6 int r = moves[i][0], c = moves[i][1];
7 int p = i % 2 == 0 ? 1 : -1;
8 rows[r] += p;
9 cols[c] += p;
10 if (r == c) diag += p;
11 if (r + c == 2) anti += p;
12 if (Math.abs(rows[r]) == 3 || Math.abs(cols[c]) == 3 || Math.abs(diag) == 3 || Math.abs(anti) == 3) {
13 return p == 1 ? "A" : "B";
14 }
15 }
16 return moves.length == 9 ? "Draw" : "Pending";
17 }
18}1class Solution {
2public:
3 string tictactoe(vector<vector<int>>& moves) {
4 int rows[3] = {0}, cols[3] = {0};
5 int diag = 0, anti = 0;
6 for (int i = 0; i < (int)moves.size(); i++) {
7 int r = moves[i][0], c = moves[i][1];
8 int p = i % 2 == 0 ? 1 : -1;
9 rows[r] += p;
10 cols[c] += p;
11 if (r == c) diag += p;
12 if (r + c == 2) anti += p;
13 if (abs(rows[r]) == 3 || abs(cols[c]) == 3 || abs(diag) == 3 || abs(anti) == 3) {
14 return p == 1 ? "A" : "B";
15 }
16 }
17 return moves.size() == 9 ? "Draw" : "Pending";
18 }
19};Time and space complexity
O(m)
Each of the m moves (at most 9) updates and checks at most four counters in constant time.
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
diagandanti. - 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.