Configurable N×N Tic-Tac-Toe in React with O(N) Win Detection
System DesignModel answerLast updated
Build a two-player, grid-size-configurable Tic-Tac-Toe React component with efficient win detection, prop reactivity, and full keyboard/screen-reader accessibility.
Flexible Grid Tic-Tac-Toe
Build a self-contained, two-player Tic-Tac-Toe component in React that works on any square grid from 3×3 up to 20×20. The board dimensions are controlled by a single size prop.
Rules of the game
- Player X always moves first, then players alternate.
- A player wins by filling an entire row, column, or diagonal with their mark — all
Ncells in that line. - If every cell is filled and no one has won, the game is a draw.
- Clicking a cell that is already taken, or clicking anything after the game ends, must have no visible effect.
What to implement
1. Board rendering
Render a grid of N × N clickable cells driven by the size prop. Fall back to 3 when size is omitted, not a whole number, or outside the range [3, 20].
2. Turn and move management Track whose turn it is and prevent illegal moves (occupied cells, moves after game over).
3. Win and draw detection
Determine the outcome immediately after each move, without scanning the whole board. At N = 20 the grid has 400 cells; your detection logic must run in O(N) time per move (checking only the row, column, and diagonals touched by the last move).
4. Status line Display one of the following at all times:
Turn: X/Turn: O— while the game is in progressWinner: X/Winner: O— when someone winsDraw!— when all cells are filled with no winner
5. Reset button A reset action clears the board and restarts the game without unmounting the component.
6. Prop reactivity
When size changes at runtime, the game must reset immediately to match the new board dimensions.
7. Accessibility
- Mark the grid with
role="grid", rows withrole="row", and cells withrole="gridcell". - Cells must be reachable and activatable via keyboard (Tab to focus, Enter or Space to play).
- Status changes (turn, winner, draw) must be announced automatically to screen readers using an
aria-liveregion. - Finished or occupied cells should remain visible and focusable; use
aria-disabledrather than thedisabledattribute so they stay in the tab order.
Component signature
interface TicTacToeProps {
size?: number; // whole number 3–20, default 3
}
export const TicTacToe: React.FC<TicTacToeProps> = ({ size = 3 }) => {
// your implementation
};
Required data-testid attributes
| Attribute | Element |
|---|---|
status | The status text element |
cell-{row}-{col} | Each cell button, zero-indexed (e.g. cell-0-0, cell-2-1) |
reset-button | The reset button |
Constraints and edge cases to handle
sizevalues that areundefined,NaN, non-integers, strings,< 3, or> 20must all silently fall back to3.- A win on the very last empty cell is a win, not a draw.
- The center cell of an odd-sized board lies on both diagonals — both counters must be updated.
- Resetting mid-game must not unmount the component.
Hints
Hint 1
Rather than re-scanning the whole board after each move, keep a running counter per row, per column, and one for each diagonal. Increment by +1 for X and -1 for O. A counter reaching +N means X filled that line; -N means O did.
Hint 2
Use a useReducer with a plain action object for every state transition (play, reset). All guard logic — occupied cell, game already over — lives inside the reducer and returns the unchanged state object for illegal moves, which prevents React from triggering a re-render.
Hint 3
Handling a size prop change cleanly: pass a key={n} to an inner Game component. When n changes, React unmounts and remounts that subtree with fresh state, avoiding the stale-frame issue you get with a useEffect-based reset.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the problem into two independent concerns: game logic (a pure reducer with counter-based win detection) and presentation (grid rendering, accessibility, prop normalization).
Win detection in O(N) per move
The standard mistake is to scan every row, column, and diagonal after each move — that's O(N²). The insight is that a new win must include the cell just played. So only four lines are relevant: the row, the column, and the two diagonals (each only if the move falls on them). Checking four scalar values is O(1); copying the counter arrays is O(N).
Track the state with integer counters:
rows[r]— running sum for rowrcols[c]— running sum for columncdiag— running sum for the main diagonal (r === c)anti— running sum for the anti-diagonal (r + c === N − 1)
Each X play adds +1, each O play adds −1. A counter reaching +N means X owns that line; −N means O does. This is correct because the only way to reach ±N from values in {−1, +1} is if all N values are the same sign.
State ownership and guard logic
All mutable state — board, counters, turn, winner, move count — lives in a single reducer. The reducer returns the same state reference for any illegal move (occupied cell, game already over). React then skips re-rendering entirely, which is the cleanest way to satisfy the "no effect" requirement.
import React, { memo, useCallback, useReducer } from "react";
type Player = "X" | "O";
type Cell = Player | null;
interface TicTacToeProps {
size?: number;
}
interface GameState {
n: number;
board: Cell[];
rows: number[];
cols: number[];
diag: number;
anti: number;
moves: number;
turn: Player;
winner: Player | null;
}
type Action = { type: "play"; r: number; c: number } | { type: "reset" };
const normalizeSize = (size: unknown): number =>
typeof size === "number" &&
Number.isInteger(size) &&
size >= 3 &&
size <= 20
? size
: 3;
const init = (n: number): GameState => ({
n,
board: Array(n * n).fill(null),
rows: Array(n).fill(0),
cols: Array(n).fill(0),
diag: 0,
anti: 0,
moves: 0,
turn: "X",
winner: null,
});
function reducer(state: GameState, action: Action): GameState {
if (action.type === "reset") return init(state.n);
const { n, board, turn, winner, moves } = state;
const { r, c } = action;
const idx = r * n + c;
// Guard: occupied cell or game already finished
if (winner || moves === n * n || board[idx] !== null) return state;
const delta = turn === "X" ? 1 : -1;
const nextBoard = board.slice();
nextBoard[idx] = turn;
const rows = state.rows.slice();
const cols = state.cols.slice();
rows[r] += delta;
cols[c] += delta;
const diag = r === c ? state.diag + delta : state.diag;
const anti = r + c === n - 1 ? state.anti + delta : state.anti;
const target = delta * n;
const won =
rows[r] === target ||
cols[c] === target ||
(r === c && diag === target) ||
(r + c === n - 1 && anti === target);
return {
n,
board: nextBoard,
rows,
cols,
diag,
anti,
moves: moves + 1,
turn: turn === "X" ? "O" : "X",
winner: won ? turn : null,
};
}
// ── Cell ────────────────────────────────────────────────────────────────────
interface CellProps {
r: number; c: number; value: Cell; over: boolean;
onPlay: (r: number, c: number) => void;
}
const BoardCell = memo(function BoardCell({ r, c, value, over, onPlay }: CellProps) {
const inactive = over || value !== null;
return (
<div role="gridcell">
<button
data-testid={`cell-${r}-${c}`}
aria-label={value ?? (inactive ? "unavailable" : `row ${r + 1} col ${c + 1}`)}
aria-disabled={inactive}
tabIndex={0}
onClick={() => onPlay(r, c)}
style={{ width: 48, height: 48, fontSize: 20, cursor: inactive ? "default" : "pointer" }}
>
{value ?? ""}
</button>
</div>
);
});
// ── Game ────────────────────────────────────────────────────────────────────
function Game({ n }: { n: number }) {
const [state, dispatch] = useReducer(reducer, n, init);
const onPlay = useCallback((r: number, c: number) =>
dispatch({ type: "play", r, c }), []);
const isDraw = !state.winner && state.moves === n * n;
const over = state.winner !== null || isDraw;
const status = state.winner
? `Winner: ${state.winner}`
: isDraw ? "Draw!"
: `Turn: ${state.turn}`;
const gridRows = [];
for (let r = 0; r < n; r++) {
const cells = [];
for (let c = 0; c < n; c++) {
cells.push(
<BoardCell
key={c} r={r} c={c}
value={state.board[r * n + c]}
over={over}
onPlay={onPlay}
/>
);
}
gridRows.push(<div key={r} role="row">{cells}</div>);
}
return (
<div>
<div
data-testid="status"
aria-live="polite"
aria-atomic="true"
>
{status}
</div>
<div role="grid" aria-label={`${n} by ${n} tic-tac-toe board`}>
{gridRows}
</div>
<button
data-testid="reset-button"
onClick={() => dispatch({ type: "reset" })}
>
Reset
</button>
</div>
);
}
// ── Public component ────────────────────────────────────────────────────────
export const TicTacToe: React.FC<TicTacToeProps> = ({ size = 3 }) => {
const n = normalizeSize(size);
// key change remounts Game with clean state; no stale frame unlike useEffect
return <Game key={n} n={n} />;
};
Complexity
| Operation | Time | Space |
|---|---|---|
| Win/draw check per move | O(1) — four counter comparisons | — |
| Reducer state update | O(N) — copying counter arrays | O(N²) total state |
| Re-render after a move | O(1) — memo means only the changed cell + status re-render | — |
The outcome check is O(1). Copying a 400-element flat array at N=20 is negligible. Initial render is inherently O(N²) regardless of approach.
Common mistakes and trade-offs
disabled vs aria-disabled: Using the disabled attribute removes cells from the tab order and hides them from some screen readers. aria-disabled keeps the element interactive in the DOM while communicating its state semantically — the reducer guard stops any actual state change.
key vs useEffect for prop reactivity: A useEffect that resets state when size changes will render one frame with the stale board before the effect fires. Placing key={n} on the inner Game component causes React to unmount and remount it synchronously — no stale frame, no extra effect logic.
Win on the final cell: The reducer checks for a winner before checking for a draw. Since won is evaluated before comparing moves + 1 === n * n, a win on the last cell correctly surfaces as a win.
Both diagonals at the center cell: When n is odd, the center cell at (n/2, n/2) satisfies both r === c and r + c === n − 1. Both diag and anti must be updated — the code handles this because both branches are independent if conditions, not else if.
Memo and useCallback: Without memo on BoardCell, every move triggers a full re-render of all N² cells. With stable onPlay via useCallback and memo, only the newly played cell and the status line re-render.
Natural follow-up: K-in-a-row (Gomoku)
If the win condition changes to K consecutive marks (e.g. K=5 on a 20×20 board) rather than a full line, the counter approach breaks — a line can have K matching marks without filling all N cells. The fix: after each move, scan outward from that cell in all four directions, counting consecutive marks of the current player. That check is O(K) per move, which is still very efficient.