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.
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.