#1275

Find Winner on a Tic Tac Toe Game

Easy
ArrayHash TableMatrixSimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a more efficient approach by tracking the counts of marks in rows, columns, and diagonals. This allows us to determine the winner without checking the entire board after each move.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize counters for rows, columns, and two diagonals.
  2. 2Step 2: Iterate through the moves and update the respective counters based on the player's turn.
  3. 3Step 3: After each move, check if any row, column, or diagonal has reached 3 for either player.
  4. 4Step 4: If a player wins, return their character ('A' or 'B').
  5. 5Step 5: If all moves are played and no winner, return 'Draw'. If moves remain, return 'Pending'.
solution.py14 lines
1# Full working Python code
2class Solution:
3    def tictactoe(self, moves):
4        rows, cols = [0]*3, [0]*3
5        diag1, diag2 = 0, 0
6        for i, move in enumerate(moves):
7            player = 1 if i % 2 == 0 else -1
8            rows[move[0]] += player
9            cols[move[1]] += player
10            if move[0] == move[1]: diag1 += player
11            if move[0] + move[1] == 2: diag2 += player
12            if abs(rows[move[0]]) == 3 or abs(cols[move[1]]) == 3 or abs(diag1) == 3 or abs(diag2) == 3:
13                return 'A' if player == 1 else 'B'
14        return 'Draw' if len(moves) == 9 else 'Pending'

Complexity note: The time complexity is O(n) because we only iterate through the moves once, updating counters and checking for a winner in constant time.

  • 1Understanding how to track game states efficiently can significantly reduce time complexity.
  • 2Recognizing patterns in winning conditions can help optimize checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.