A game server hosts tic-tac-toe on boards of any size. The board is n × n, two players take cells, and a player wins by owning every cell of one row, one column, the main diagonal (top-left to bottom-right) or the anti-diagonal (top-right to bottom-left). The server must answer each move instantly, even on huge boards.
Write a class TicTacToe:
new TicTacToe(n) creates an empty n × n board. Throw a RangeError unless n is a positive safe integer.
move(row, col, player) places a mark for player (1 or 2) at row row and column col (both 0-based) and returns the winner after this move: 1 or 2, or 0 if nobody has won yet.
winner is a property: 0 until someone wins, then that player's number.
Rules:
Throw a RangeError if row or col is not an integer in 0 … n - 1, or player is not 1 or 2.
Throw an Error if the cell is already taken, or if the game already has a winner. The class does not enforce turn order: the same player may move twice in a row.
A full board with no winner is a draw: every move simply returned 0.
Boards can have n = 100,000 and games can have hundreds of thousands of moves. Each move must be O(1): do not scan a row or column, and do not allocate an n × n grid.
const game = new TicTacToe(3);game.move(0, 0, 1); // 0game.move(1, 1, 2); // 0game.move(0, 1, 1); // 0game.move(2, 2, 2); // 0game.move(0, 2, 1); // 1: player 1 owns row 0game.winner; // 1game.move(2, 0, 2); // throws Error: the game is over
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
5
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.