Design an n x n Tic-Tac-Toe Game
Company: Databricks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's ability to design a class-based data structure that tracks game state and efficiently detects a win condition after each move. It tests object-oriented design and algorithmic thinking around incremental state updates, a common focus in coding interviews for object design problems. The question requires practical implementation skill rather than purely theoretical knowledge.
Constraints
- 2 <= n <= 1000
- 0 <= row, col < n
- player is either 1 or 2
- Each move() call targets a previously empty cell
- Up to 10^5 calls to move()
- No move() is called after a winning move
Examples
Input: (['TicTacToe','move','move','move','move','move','move','move'], [[3],[0,0,1],[0,2,2],[2,2,1],[1,1,2],[2,0,1],[1,0,2],[2,1,1]])
Expected Output: [None, 0, 0, 0, 0, 0, 0, 1]
Explanation: The worked example: player 1 completes the bottom row (2,0),(2,1),(2,2) on the final move and wins.
Input: (['TicTacToe','move','move','move','move','move','move'], [[3],[0,0,1],[0,1,2],[1,0,1],[1,1,2],[2,2,1],[2,1,2]])
Expected Output: [None, 0, 0, 0, 0, 0, 2]
Explanation: Player 2's marks at (0,1),(1,1),(2,1) complete column 1, so the last move returns 2.
Input: (['TicTacToe','move','move','move','move','move'], [[3],[0,0,1],[0,1,2],[1,1,1],[0,2,2],[2,2,1]])
Expected Output: [None, 0, 0, 0, 0, 1]
Explanation: Player 1 fills the main diagonal (0,0),(1,1),(2,2); the third of those moves wins.
Input: (['TicTacToe','move','move','move','move','move','move'], [[3],[0,0,1],[0,2,2],[1,0,1],[1,1,2],[2,1,1],[2,0,2]])
Expected Output: [None, 0, 0, 0, 0, 0, 2]
Explanation: Player 2 completes the anti-diagonal (0,2),(1,1),(2,0), so the final move returns 2.
Input: (['TicTacToe','move','move','move'], [[2],[0,0,1],[1,0,2],[0,1,1]])
Expected Output: [None, 0, 0, 1]
Explanation: Boundary n=2: player 1's (0,0) and (0,1) complete row 0, so the last move wins.
Input: (['TicTacToe','move'], [[3],[1,1,1]])
Expected Output: [None, 0]
Explanation: Minimal case: a single central move on a 3x3 board cannot complete any line of length 3, so it returns 0.
Hints
- You do not need to store the full board. Track a running total per row and per column, plus one for each diagonal.
- Encode player 1 as +1 and player 2 as -1. A line is complete for player 1 when its sum reaches +n and for player 2 when it reaches -n, so check abs(sum) == n.
- Cell (row, col) is on the main diagonal when row == col, and on the anti-diagonal when row + col == n - 1. Update those counters only when the move lands on them.
- After updating the four affected counters, the move wins if any of them hits magnitude n — return the player; otherwise return 0.