Design BFS to detect forced win in Tic-Tac-Toe
Company: Databricks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithm design and search-space reasoning, focusing on BFS-based game-tree exploration, state representation, symmetry reduction and hashing, win/draw detection, pruning and move-ordering heuristics, and time/space complexity analysis in terms of n, k, t, and the branching factor within the Coding & Algorithms domain.
Constraints
- 1 <= n <= 4 and 1 <= k <= n
- 0 <= t <= 3
- board is square, contains only '.', 'X', and 'O', and the input position has at most one winner already present
Examples
Input: (["XX.", "OO.", "..."], "X", 3, 1)
Expected Output: True
Explanation: X places at the last cell of the top row to form XXX immediately.
Input: (["X..", ".O.", "..X"], "X", 3, 2)
Expected Output: True
Explanation: X can play in the top-right corner (or symmetrically bottom-left), creating two separate one-move threats. O can block only one, so X wins on its second move.
Input: (["X.O", "...", "..."], "O", 3, 0)
Expected Output: False
Explanation: O does not already have a winning line, and with t = 0 it cannot make any move.
Input: (["OOO", "X..", "..."], "X", 3, 2)
Expected Output: False
Explanation: The opponent already has a winning line, so the answer is False before any search.
Input: (["XXX", "OOO", "..."], "X", 3, 1)
Expected Output: True
Explanation: By the stated rule, if the current player already has a winning line, return True even if the opponent also has one.
Input: (["X..", ".O.", "..."], "X", 3, 1)
Expected Output: False
Explanation: X cannot complete three in a row with only one move from this position.
Input: (["."], "X", 1, 1)
Expected Output: True
Explanation: With k = 1, placing X in the only cell wins immediately.
Hints
- Build the game graph level by level only up to the move limit, then evaluate it backward. On your turn use any(...); on the opponent's turn use all(...).
- A board plus whose turn it is is a state. To avoid repeated work, hash states; for extra pruning, canonicalize the board under the 8 rotations/reflections of a square.