LeetCode 348: Design Tic-Tac-Toe Solution

Master LeetCode problem 348 (Design Tic-Tac-Toe), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

348. Design Tic-Tac-Toe

Problem Explanation

Explanation:

To design a Tic-Tac-Toe game, we can use a 2D array to represent the board. We will keep track of the rows, columns, and diagonals to determine the winner.

The idea is to update the count of 'X' and 'O' for each row, column, and diagonal as we place the marks on the board. If at any point the count reaches the board size for either player ('n' for an n x n board), that player wins.

For each move, we update the counts and check for a winner. If a player wins, we return the player number. If no player wins after all moves, we return 0 for a draw.

Time complexity: O(1) for each move Space complexity: O(n) for the board and counts arrays

: :

Solution Code

class TicTacToe {
    int n;
    int[] rows;
    int[] cols;
    int diagonal;
    int antiDiagonal;

    public TicTacToe(int n) {
        this.n = n;
        rows = new int[n];
        cols = new int[n];
        diagonal = 0;
        antiDiagonal = 0;
    }

    public int move(int row, int col, int player) {
        int val = (player == 1) ? 1 : -1;

        rows[row] += val;
        cols[col] += val;
        if (row == col) {
            diagonal += val;
        }
        if (row + col == n - 1) {
            antiDiagonal += val;
        }

        if (Math.abs(rows[row]) == n || Math.abs(cols[col]) == n || Math.abs(diagonal) == n || Math.abs(antiDiagonal) == n) {
            return player;
        }

        return 0;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 348 (Design Tic-Tac-Toe)?

This page provides optimized solutions for LeetCode problem 348 (Design Tic-Tac-Toe) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 348 (Design Tic-Tac-Toe)?

The time complexity for LeetCode 348 (Design Tic-Tac-Toe) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 348 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 348 in Java, C++, or Python.

Back to LeetCode Solutions