Detect a Tic-Tac-Toe Winner in Constant Time per Move
Last updated: November 29, 2026
Quick Overview
Design a class for an n x n tic-tac-toe game in a Messenger instant game where move(row, col, player) records a move and returns the winning player (1 or 2) or 0 if nobody has won yet. Each move must take O(1) time.
Meta
November 29, 20260
0
0 solved
Design a class for an n x n tic-tac-toe game in a Messenger instant game where move(row, col, player) records a move and returns the winning player (1 or 2) or 0 if nobody has won yet. Each move must take O(1) time.
A Meta onsite question about maintaining incremental game state rather than rescanning the board. The interviewer checks whether you replace an O(n) row/column/diagonal scan with running counters.
What the Interviewer Expects
- Start with an O(n) check of the move's row, column and diagonals
- Replace it with signed counters per row, column and two diagonals
- Use +1 for player 1 and -1 for player 2
- Detect a win when a counter reaches n in absolute value
- Use O(n) total space
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How do you support undo?
- Generalize to k-in-a-row on a large board (Gomoku).
- How would you validate moves and detect a draw?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
API: TicTacToe(n) then move(row, col, player). Moves are valid (empty cell, correct player, game not already won). Return 1 or 2 when that move wins, otherwise 0. Target: O(1) per move, O(n) memor...
High-Level Design
A player wins by owning all n cells of one row, column, the main diagonal, or the anti-diagonal. Rather than store the board, keep rows[n], cols[n], diag, and anti. Player 1 adds +1, player 2 ...