Design an efficient Tic-Tac-Toe engine
Company: Databricks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's understanding of efficient algorithm design and minimal state management for a Tic-Tac-Toe engine on an n x n board, including constraints such as O(1) time per move and O(n) space.
Constraints
- 1 <= n <= 2000
- 1 <= len(operations) <= 2 * 10^5
- Each operation is one of ("move", row, col, player), ("undo",), or ("reset",)
- Winner detection after a move should be O(1) average time without rescanning the board
Examples
Input: (3, [("move", 0, 0, 1), ("move", 0, 0, 2), ("move", 3, 0, 1), ("undo",), ("undo",)])
Expected Output: ["NONE", "INVALID", "INVALID", "UNDONE", "INVALID"]
Explanation: The second move reuses an occupied cell, the third is out of bounds, the fourth undoes the only valid move, and the final undo fails because history is empty.
Input: (3, [("move", 0, 0, 1), ("move", 0, 1, 2), ("move", 1, 1, 1), ("move", 0, 2, 2), ("move", 2, 2, 1), ("move", 2, 0, 2)])
Expected Output: ["NONE", "NONE", "NONE", "NONE", "P1", "INVALID"]
Explanation: Player 1 completes the main diagonal on the fifth command. After a win, further moves are invalid until an undo or reset happens.
Input: (3, [("move", 0, 0, 1), ("move", 0, 1, 2), ("move", 0, 2, 1), ("move", 1, 1, 2), ("move", 1, 0, 1), ("move", 1, 2, 2), ("move", 2, 1, 1), ("move", 2, 0, 2), ("move", 2, 2, 1)])
Expected Output: ["NONE", "NONE", "NONE", "NONE", "NONE", "NONE", "NONE", "NONE", "DRAW"]
Explanation: All cells are filled without any row, column, or diagonal being completed by a single player.
Input: (1, [("move", 0, 0, 3), ("move", 0, 0, 2), ("undo",), ("move", 0, 0, 1)])
Expected Output: ["INVALID", "P2", "UNDONE", "P1"]
Explanation: Player 3 is invalid. On a 1x1 board, the first valid move wins immediately. Undo reopens the game, allowing the last move.
Input: (3, [("move", 0, 0, 1), ("move", 1, 1, 2), ("reset",), ("undo",), ("move", 2, 2, 1)])
Expected Output: ["NONE", "NONE", "RESET", "INVALID", "NONE"]
Explanation: Reset clears both the board and move history, so the following undo is invalid.
Input: (2, [("move", 0, 0, 1), ("undo", 1), ("foo",), ("reset",), ("move", 1, 1, 2)])
Expected Output: ["NONE", "INVALID", "INVALID", "RESET", "NONE"]
Explanation: Malformed and unknown commands are invalid and do not affect the board. Reset clears the earlier move.
Hints
- Track each row and column with a running balance: +1 for player 1 and -1 for player 2. If any absolute value reaches n, that player has won.
- For undo, store each valid move on a stack so you can subtract its contribution from the row, column, and diagonal counters.