KatInterview

348. Design Tic-Tac-Toe

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to design a Tic-Tac-Toe game on an n x n board. The core challenge is to efficiently determine if a player has won after each move. A win occurs when a player places n of their marks in a single row, column, or one of the two main diagonals. A naive approach of checking the entire board after each move would be too slow, especially given the constraint n can be up to 100. The follow-up question hints at an O(1) solution for the move operation, which suggests we should avoid any form of iteration over the board's rows or columns.

Solution

Design Tic-Tac-Toe in Python

class TicTacToe:

    def __init__(self, n: int):
        """
        Initialize your data structure here.
        """
        self.n = n
        # Use arrays to store the sum of moves for each row and column.
        # A move by player 1 adds 1, a move by player 2 adds -1.
        self.rows = [0] * n
        self.cols = [0] * n
        # Store the sum of moves for the two main diagonals.
        self.diagonal = 0
        self.anti_diagonal = 0

    def move(self, row: int, col: int, player: int) -> int:
        """
        Player {player} makes a move at ({row}, {col}).
        @param row The row of the board.
        @param col The column of the board.
        @param player The player, can be either 1 or 2.
        @return The current winning condition, can be either:
                0: No one wins.
                1: Player 1 wins.
                2: Player 2 wins.
        """
        # Determine the value to add to counters based on the player.
        # Player 1: +1, Player 2: -1.
        to_add = 1 if player == 1 else -1
        
        # Update the counters for the current row and column.
        self.rows[row] += to_add
        self.cols[col] += to_add
        
        # If the move is on the main diagonal, update the diagonal counter.
        if row == col:
            self.diagonal += to_add
        
        # If the move is on the anti-diagonal, update the anti-diagonal counter.
        if row + col == self.n - 1:
            self.anti_diagonal += to_add
            
        # Check if the current move results in a win.
        # A win occurs if any counter's absolute value equals n.
        if abs(self.rows[row]) == self.n or \
           abs(self.cols[col]) == self.n or \
           abs(self.diagonal) == self.n or \
           abs(self.anti_diagonal) == self.n:
            return player
            
        # If no one has won, return 0.
        return 0


# Your TicTacToe object will be instantiated and called as such:
# obj = TicTacToe(n)
# param_1 = obj.move(row,col,player)

Design Tic-Tac-Toe in Java

class TicTacToe {
    private int n;
    // Use arrays to store the sum of moves for each row and column.
    // A move by player 1 adds 1, a move by player 2 adds -1.
    private int[] rows;
    private int[] cols;
    // Store the sum of moves for the two main diagonals.
    private int diagonal;
    private int antiDiagonal;

    public TicTacToe(int n) {
        this.n = n;
        this.rows = new int[n];
        this.cols = new int[n];
        this.diagonal = 0;
        this.antiDiagonal = 0;
    }
    
    public int move(int row, int col, int player) {
        // Determine the value to add to counters based on the player.
        // Player 1: +1, Player 2: -1.
        int toAdd = (player == 1) ? 1 : -1;
        
        // Update the counters for the current row and column.
        rows[row] += toAdd;
        cols[col] += toAdd;
        
        // If the move is on the main diagonal, update the diagonal counter.
        if (row == col) {
            diagonal += toAdd;
        }
        
        // If the move is on the anti-diagonal, update the anti-diagonal counter.
        if (row + col == n - 1) {
            antiDiagonal += toAdd;
        }
        
        // Check if the current move results in a win.
        // A win occurs if any counter's absolute value equals n.
        if (Math.abs(rows[row]) == n ||
            Math.abs(cols[col]) == n ||
            Math.abs(diagonal) == n ||
            Math.abs(antiDiagonal) == n) {
            return player;
        }
        
        // If no one has won, return 0.
        return 0;
    }
}

/**
 * Your TicTacToe object will be instantiated and called as such:
 * TicTacToe obj = new TicTacToe(n);
 * int param_1 = obj.move(row,col,player);
 */

Design Tic-Tac-Toe in C++

class TicTacToe {
private:
    // Store the size of the board.
    int n;
    // Use arrays to store the sum of moves for each row and column.
    // A move by player 1 adds 1, a move by player 2 adds -1.
    std::vector<int> rows;
    std::vector<int> cols;
    // Store the sum of moves for the two main diagonals.
    int diagonal;
    int antiDiagonal;

public:
    TicTacToe(int n) {
        this->n = n;
        this->rows.resize(n, 0);
        this->cols.resize(n, 0);
        this->diagonal = 0;
        this->antiDiagonal = 0;
    }
    
    int move(int row, int col, int player) {
        // Determine the value to add to counters based on the player.
        // Player 1: +1, Player 2: -1.
        int toAdd = (player == 1) ? 1 : -1;
        
        // Update the counters for the current row and column.
        rows[row] += toAdd;
        cols[col] += toAdd;
        
        // If the move is on the main diagonal, update the diagonal counter.
        if (row == col) {
            diagonal += toAdd;
        }
        
        // If the move is on the anti-diagonal, update the anti-diagonal counter.
        if (row + col == n - 1) {
            antiDiagonal += toAdd;
        }
        
        // Check if the current move results in a win.
        // A win occurs if any counter's absolute value equals n.
        if (std::abs(rows[row]) == n ||
            std::abs(cols[col]) == n ||
            std::abs(diagonal) == n ||
            std::abs(antiDiagonal) == n) {
            return player;
        }
        
        // If no one has won, return 0.
        return 0;
    }
};

/**
 * Your TicTacToe object will be instantiated and called as such:
 * TicTacToe* obj = new TicTacToe(n);
 * int param_1 = obj->move(row,col,player);
 */

Design Tic-Tac-Toe in TypeScript

class TicTacToe {
    private n: number;
    // Use arrays to store the sum of moves for each row and column.
    // A move by player 1 adds 1, a move by player 2 adds -1.
    private rows: number[];
    private cols: number[];
    // Store the sum of moves for the two main diagonals.
    private diagonal: number;
    private antiDiagonal: number;

    constructor(n: number) {
        this.n = n;
        this.rows = new Array(n).fill(0);
        this.cols = new Array(n).fill(0);
        this.diagonal = 0;
        this.antiDiagonal = 0;
    }

    move(row: number, col: number, player: number): number {
        // Determine the value to add to counters based on the player.
        // Player 1: +1, Player 2: -1.
        const toAdd = player === 1 ? 1 : -1;

        // Update the counters for the current row and column.
        this.rows[row] += toAdd;
        this.cols[col] += toAdd;

        // If the move is on the main diagonal, update the diagonal counter.
        if (row === col) {
            this.diagonal += toAdd;
        }

        // If the move is on the anti-diagonal, update the anti-diagonal counter.
        if (row + col === this.n - 1) {
            this.antiDiagonal += toAdd;
        }

        // Check if the current move results in a win.
        // A win occurs if any counter's absolute value equals n.
        if (Math.abs(this.rows[row]) === this.n ||
            Math.abs(this.cols[col]) === this.n ||
            Math.abs(this.diagonal) === this.n ||
            Math.abs(this.antiDiagonal) === this.n) {
            return player;
        }

        // If no one has won, return 0.
        return 0;
    }
}

/**
 * Your TicTacToe object will be instantiated and called as such:
 * var obj = new TicTacToe(n)
 * var param_1 = obj.move(row,col,player)
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.