Design Tic-Tac-Toe

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-06-09

Problem Statement

Design and implement the core logic for a Tic-Tac-Toe game that allows two players to play on a N × N grid (commonly 3 × 3).


The design should handle game state management, move validation, and win/draw detection.


🧠 Functional Requirements


Initialize Game

•Allow creation of a game with a configurable board size (default = 3 × 3).
•Two players take turns (X and O).

Make a Move

•A player can mark any empty cell with their symbol.
•Moves must be validated (no overwriting existing cells, within bounds).

Check Game Status

•After each move, check whether:
•The current player wins.
•The board is full (draw).
•The game should continue.

Display Board

•Provide a method to print or return the current board state.

Restart / Reset

•Optionally allow resetting the game board for a new round.


🚫 Non-Functional Requirements


•Code should be modular, testable, and object-oriented.
•Design should allow different board sizes and player types (e.g., human vs. AI).
•Time complexity for checking a winner should ideally be O(1) per move (using counters or tracking).


🧱 Suggested Classes


ClassResponsibility


Game

Main class that controls the game flow, player turns, and win detection.


Board

Manages grid state, cell updates, and validation logic.


Player

Represents a player with name and symbol (X/O).


Cell

Represents each cell on the board with coordinates and value.


GameStatus (Enum)

Enum for IN_PROGRESS, WIN, DRAW.


🔄 Example Flow


1.Initialize Game
1 2game = new Game(3)
1.Players take turns:
1 2Player 1 (X) → move(0,0) 3Player 2 (O) → move(0,1) 4Player 1 (X) → move(1,1) 5Player 2 (O) → move(0,2) 6Player 1 (X) → move(2,2)
1.System checks for win after each move.
2.Declares “Player 1 (X) wins!”

🧪 Example Input / Output


Input:

1 2Board Size = 3 3Moves: 4X 0 0 5O 0 1 6X 1 1 7O 0 2 8X 2 2


Output:

1 2Player X wins! 3Final Board: 4X O O 5_ X _ 6_ _ X


⚙️ Constraints


•2 players
•Board size: 3 ≤ N ≤ 10
•All moves valid within range (0 ≤ row, col < N)
•O(1) or O(N) win-check per move


🎯 Goals


•Clear class design and relationships.
•Maintainable logic for win detection (row, column, diagonal tracking).
•Extendable to:
•NxN board.
•Human vs. AI mode.
•Multiplayer / Online version.


✅ In short:


Design the classes, interactions, and logic for a Tic-Tac-Toe game supporting configurable board size, turn management, and efficient win detection.

Solution

Comments