Find Winner on a Tic Tac Toe Game — LeetCode 1275 Python Solution

EasyArrayHash TableMatrixSimulation
Problem
#1275
Reading time
3 min

The problem

Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are: Players take turns placing characters into empty squares ' '.

Example

Input
moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
Output
"A"
Explanation
A wins, they always play first.

Python solution

Python
class Solution:
    def tictactoe(self, moves: List[List[int]]) -> str:
        n = len(moves)
        cnt = [0] * 8
        for k in range(n - 1, -1, -2):
            i, j = moves[k]
            cnt[i] += 1
            cnt[j + 3] += 1
            if i == j:
                cnt[6] += 1
            if i + j == 2:
                cnt[7] += 1
            if any(v == 3 for v in cnt):
                return "B" if k & 1 else "A"
        return "Draw" if n == 9 else "Pending"

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1275. Find Winner on a Tic Tac Toe Game is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1275. Find Winner on a Tic Tac Toe Game?
LeetCode 1275. Find Winner on a Tic Tac Toe Game is rated Easy on LeetCode.
What is the time complexity of LeetCode 1275. Find Winner on a Tic Tac Toe Game?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1275. Find Winner on a Tic Tac Toe Game?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1275. Find Winner on a Tic Tac Toe Game cover?
LeetCode 1275. Find Winner on a Tic Tac Toe Game is tagged Array, Hash Table, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview