All questions

Tic-tac-toe II

Premium

Tic-tac-toe II

Generalize tic-tac-toe to an N×N board where M consecutive marks win. The fixed 3×3 board with eight hard-coded lines doesn't scale — for a 9×9 board you can't list every line by hand. Instead, store the board as a flat array and detect a win by scanning from each filled cell along four directions for M in a row.

Signature

type Mark = 'X' | 'O' | null;
function getWinner(board: Mark[], size: number, target: number): Mark;

// A self-contained component. No props.
function App(): JSX.Element;

Examples

size = 5, target = 4 → place 4 X's in a row/col/diagonal to win
size = 3, target = 3 → classic tic-tac-toe
cell at row r, column c lives at flat index r * size + c
scan directions: → (0,1), ↓ (1,0), ↘ (1,1), ↙ (1,-1)

Notes

  • Flat board + index math. board[r * size + c]; don't hard-code line lists.
  • Scan, don't enumerate. From each filled cell, step up to M-1 along 4 directions; M in a row wins.
  • Parameterized. size and target come from controls; changing either resets the board.
  • Out of scope. Unbeatable AI, gravity (that's Connect Four) — two human players here.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium