♟️ From Tic-Tac-Toe to Sudoku — master the board with pattern recognition
Welcome to the board game arena! This is where you learn to DESIGN board games, SIMULATE cellular automata, SOLVE constraint puzzles, and VALIDATE game states. We're covering the most iconic board-based problems that appear in FAANG interviews: Tic-Tac-Toe Design, Game of Life, Snake Game, N-Queens, Sudoku, Sliding Puzzle, and Word Search. The common thread? Every problem involves a grid or board with state transitions. Whether it's a queen attacking diagonally, a cell living or dying, or a snake slithering — the core skill is modeling state on a 2D grid.
Tic-Tac-ToeGame of LifeSnakeN-QueensSudokuSliding PuzzleWord Search12 Problems
🤔 Why Board Games Matter: The Grid Mindset
Imagine you're asked to design Tic-Tac-Toe in an interview. Sounds simple, right? But then they ask: "Can you check a win in O(1) time?" Or: "Can you support an N×N board where N is 1000?"
Board game problems test your ability to think in 2D space. They combine array indexing, state machines,backtracking, and optimization — all in one neat grid. Here's what makes them special:
Grid as state — The board IS the state. Every cell matters.
Constraints — No two queens share a diagonal; no repeated digits in a row.
Simulation — Game of Life evolves one generation at a time.
Optimal play — Can you force a win in Tic-Tac-Toe?
Tip
💡 The Grid Mindset: Whenever you see a problem with a 2D grid, immediately think: "How do I index this? What are the directions? What are the constraints?" The answer is almost always about efficient indexingand constraint propagation.
Tic-Tac-Toe is the "Hello World" of board game design. But don't underestimate it — Amazon and Microsoft LOVE this problem because it tests clean API design,O(1) win detection, and state validation.
Note
🎪 Real-World Analogy: Think of a manager with a scoreboard at a company tournament. The manager doesn't check every player after every move — they just update running totals for each team. When any team's score hits the target, they declare a winner. That's exactly how efficient Tic-Tac-Toe works! Track row/col/diag scores, don't scan the board.
🔍 Real-Time Thinking — The O(1) Win Check
"I need to check if someone won after every move. Scanning the whole board is O(n²) per move. But wait — only the row, column, and diagonals of the last move could have changed. What if I maintain running sums for each row, column, and both diagonals?"
Player 1 places an X → add +1 to that row/col/diag. Player 2 places an O → subtract 1. If any running sum reaches ±n, that player wins. O(1) per move!
Tic-Tac-Toe Board State and Win Detection
Design Tic-Tac-Toe — The O(1) Solution
example.js
class TicTacToe {
constructor(n) {
this.n = n;
this.rows = new Array(n).fill(0); // Running scores per row
this.cols = new Array(n).fill(0); // Running scores per col
this.diag = 0; // Main diagonal
this.antiDiag = 0; // Anti-diagonal
}
move(row, col, player) {
// Player 1 = +1, Player 2 = -1
const score = player === 1 ? 1 : -1;
this.rows[row] += score;
this.cols[col] += score;
if (row === col) this.diag += score; // Main diagonal
if (row === this.n - col - 1) this.antiDiag += score; // Anti-diagonal
// Check if this move won the game
if (Math.abs(this.rows[row]) === this.n ||
Math.abs(this.cols[col]) === this.n ||
Math.abs(this.diag) === this.n ||
Math.abs(this.antiDiag) === this.n) {
return player;
}
return 0; // No winner yet
}
}
Time: O(1) per move. Space: O(n) for rows, O(n) for cols, O(1) for diagonals.
Valid Tic-Tac-Toe State — The Validation Rules
Given a 3×3 board, determine if it's a reachable state. This is a DIFFERENT problem — you're not designing the game, you're checking if a given board could have occurred through legal play.
Three rules must hold:
example.js
function validTicTacToe(board) {
let xCount = 0, oCount = 0;
for (const row of board) {
for (const cell of row) {
if (cell === 'X') xCount++;
if (cell === 'O') oCount++;
}
}
// Rule 1: X goes first, so X is always >= O
if (oCount > xCount || xCount > oCount + 1) return false;
// Rule 2: Check if X wins
const xWin = checkWin(board, 'X');
const oWin = checkWin(board, 'O');
// Rule 3: Both can't win simultaneously
if (xWin && oWin) return false;
// Rule 4: If X wins, X must have exactly one more than O
if (xWin && xCount !== oCount + 1) return false;
// Rule 5: If O wins, counts must be equal (O just played)
if (oWin && xCount !== oCount) return false;
return true;
}
function checkWin(board, player) {
// Check rows, cols, diagonals
const lines = [
[0,0,0,1,0,2], [1,0,1,1,1,2], [2,0,2,1,2,2], // rows
[0,0,1,0,2,0], [0,1,1,1,2,1], [0,2,1,2,2,2], // cols
[0,0,1,1,2,2], [0,2,1,1,2,0], // diags
];
for (const [r1,c1,r2,c2,r3,c3] of lines) {
if (board[r1][c1] === player &&
board[r2][c2] === player &&
board[r3][c3] === player) return true;
}
return false;
}
📋 Edge Cases to Consider
First move must be X — X count is always ≥ O count.
X wins → X played last — X count must be O count + 1.
O wins → O played last — counts must be equal.
Both winners? Impossible — game stops at first win.
Problem (Leetcode 289): Conway's Game of Life is a cellular automaton where cells live, die, or are born based on neighbor counts. Given a board, compute its next generationin-place.
Note
🧬 Real-World Analogy: Imagine a city block where residents follow a simple rule: "If I have too few neighbors, I move out. If I have too many, I move out. If I have just the right number, I stay. If I'm in an empty house with exactly three neighbors, I move in." The city planner (you) must update everyone's status SIMULTANEOUSLY — no cheating by looking at already-updated neighbors!
🔍 Real-Time Thinking — The Encoding Trick
"I need to update every cell based on its 8 neighbors. But if I update a cell right away, the next cell will see the NEW state instead of the OLD state. I need to store both old and new values. I could use a copy — but they said in-place. What if I encode two bits in one integer? Old state occupies bit 0. New state occupies bit 1. Then I process: first pass writes the new bit. Second pass shifts to extract the new state!"
Conway's Game of Life Cell Transition Rules
The Encoding Scheme
Old State
New State
Encoded Value
Binary
Meaning
0 (dead)
0 (dead)
0
00
Stays dead
1 (alive)
0 (dead)
1
01
Dies (over/under-population)
0 (dead)
1 (alive)
2
10
Born (reproduction)
1 (alive)
1 (alive)
3
11
Survives
example.js
function gameOfLife(board) {
const rows = board.length, cols = board[0].length;
// Directions: 8 neighbors
const dirs = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]];
// Pass 1: Encode new state in bit 1
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
let live = 0;
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) {
live += board[nr][nc] & 1; // Read old state (bit 0)
}
}
const old = board[r][c] & 1;
if (old === 1) {
// Cell is alive: survives with 2-3 neighbors
if (live === 2 || live === 3) board[r][c] = 3; // 11
} else {
// Cell is dead: born with exactly 3 neighbors
if (live === 3) board[r][c] = 2; // 10
}
}
}
// Pass 2: Shift to extract new state
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
board[r][c] >>= 1; // New state is now in bit 0
}
}
return board;
}
Key Insight
🔑 The Encoding Trick: By using two bits per cell (old=bit0, new=bit1), we preserve the ORIGINAL state for neighbor counting while writing the NEW state. The second pass extracts the new state by right-shifting. This is an essential technique for in-place grid transformations!
📋 Edge Cases to Consider
1×1 board: A single cell has no neighbors (all 8 directions out of bounds). It dies of underpopulation.
1×N or N×1 board: Each cell has at most 3 neighbors. Handle boundary checking carefully.
Board with all dead cells: No live neighbors = no births. Board stays all zeros.
Stable patterns (block, beehive): These stay unchanged between generations. The encoding handles them correctly.
Oscillators (blinker, toad): Period-2 patterns that flip back and forth. Each generation is computed independently.
Problem (Leetcode 353): Design a Snake game that moves on an M×N board. The snake grows when it eats food. The game ends when the snake hits a wall or itself.
Note
🐍 Real-World Analogy: The snake is like a train moving through a grid. The head leads, and each car follows the exact path of the car in front. When the train eats food (a station), it adds a new car. The challenge is tracking where ALL cars are — you need to know the head's position, the tail's position, and every segment in between.
🔍 Real-Time Thinking — Why a Queue?
"The snake moves one step at a time. The head moves forward. The tail follows — or if we just ate food, the tail stays. This is a FIFO pattern: the head enters a new cell (enqueue), the tail leaves its cell (dequeue) unless we just ate. A queue perfectly models the snake's body! And I need a set for O(1) collision detection with the body."
Snake Movement Visualization
Step
Direction
Head Position
Body (Queue)
Ate Food?
Length
Start
—
(0, 0)
[(0,0)]
—
1
1
RIGHT
(0, 1)
[(0,0), (0,1)]
✓
2
2
RIGHT
(0, 2)
[(0,0), (0,1), (0,2)]
✗
2 (tail (0,0) removed)
3
DOWN
(1, 2)
[(0,1), (0,2), (1,2)]
✗
2 (tail (0,1) removed)
4
LEFT
(1, 1)
[(0,2), (1,2), (1,1)]
✓
3
example.js
class SnakeGame {
constructor(width, height, food) {
this.width = width;
this.height = height;
this.food = food;
this.foodIndex = 0;
this.snake = new Queue();
this.snake.enqueue([0, 0]); // Initial head at (0,0)
this.body = new Set(["0,0"]); // Set for O(1) body collision
this.score = 0;
}
move(direction) {
// Get current head position
const [headR, headC] = this.snake.peekLast();
// Compute new head position
let [newR, newC] = [headR, headC];
if (direction === "U") newR--;
else if (direction === "D") newR++;
else if (direction === "L") newC--;
else if (direction === "R") newC++;
// Check wall collision
if (newR < 0 || newR >= this.height ||
newC < 0 || newC >= this.width) return -1;
// Check if eating food
const eating = this.foodIndex < this.food.length &&
newR === this.food[this.foodIndex][0] &&
newC === this.food[this.foodIndex][1];
// Remove tail if NOT eating (FIFO)
if (!eating) {
const [tailR, tailC] = this.snake.dequeue();
this.body.delete(tailR + "," + tailC);
} else {
this.foodIndex++;
this.score++;
}
// Check body collision (after tail removal for edge case)
const key = newR + "," + newC;
if (this.body.has(key)) return -1;
// Move head
this.snake.enqueue([newR, newC]);
this.body.add(key);
return this.score;
}
}
📋 Edge Cases to Consider
Snake eating itself: The new head position already has a body segment. Check body BEFORE enqueuing.
Snake eating and growing into its own tail: The tail moves away when eating? NO — when eating, tail stays! But check body collision AFTER removing the tail (the tail cell may be the new head position — that's OK since tail left).
Multiple food items: Food is consumed in order. Once eaten, the next food becomes active.
Food on initial position? Snake starts at (0,0). If food is also at (0,0), the snake eats it on the first move toward it, not before moving.
Wrap-around: This version doesn't wrap (wall = death). Some variations allow teleporting — adjust collision check.
Out-of-bounds food: Food coordinates are guaranteed to be valid (per problem constraints).
Place N queens on an N×N chessboard so that no two queens attack each other. Queens attack along rows, columns, and diagonals.
Note
👑 Real-World Analogy: Imagine you're arranging VIP guests at a rectangular dinner table. Each guest (queen) demands that no other guest sits in their row, column, or diagonal sightline. You need to seat ALL N guests. Every time you place someone, you cross off their entire row, column, and diagonals — no one else can sit there!
🔍 Real-Time Thinking — The 3-Guard System
"I need to place queens row by row. For each row, I try every column. But before placing, I check if this column is already attacked. How? Three guards:Same column → is this column already used?Main diagonal → all cells on (row - col) are on the same NW-SE diagonal.Anti-diagonal → all cells on (row + col) are on the same NE-SW diagonal."
N-Queens (N=4) — Valid Placement Trace. Place one queen per row; reject repeated columns and diagonals. One valid N=4 solution is [1,3,0,2].
example.js
function solveNQueens(n) {
const solutions = [];
const board = Array.from({ length: n }, () => new Array(n).fill("."));
// Constraint tracking — O(1) checks
const cols = new Array(n).fill(false); // Column guard
const diag1 = new Array(2 * n - 1).fill(false); // Main diagonal (row - col)
const diag2 = new Array(2 * n - 1).fill(false); // Anti-diagonal (row + col)
function backtrack(row) {
if (row === n) {
solutions.push(board.map(r => r.join("")));
return;
}
for (let col = 0; col < n; col++) {
const d1 = row - col + n - 1; // Offset to make index non-negative
const d2 = row + col;
// Check all three guards
if (cols[col] || diag1[d1] || diag2[d2]) continue;
// Place queen
board[row][col] = "Q";
cols[col] = diag1[d1] = diag2[d2] = true;
backtrack(row + 1);
// Remove queen (backtrack)
board[row][col] = ".";
cols[col] = diag1[d1] = diag2[d2] = false;
}
}
backtrack(0);
return solutions;
}
N-Queens II — Just Count the Solutions
N-Queens II is the same problem but only asks for the count of solutions. Same backtracking, but increment a counter instead of collecting boards:
example.js
function totalNQueens(n) {
let count = 0;
const cols = new Array(n).fill(false);
const diag1 = new Array(2 * n - 1).fill(false);
const diag2 = new Array(2 * n - 1).fill(false);
function backtrack(row) {
if (row === n) { count++; return; }
for (let col = 0; col < n; col++) {
const d1 = row - col + n - 1;
const d2 = row + col;
if (cols[col] || diag1[d1] || diag2[d2]) continue;
cols[col] = diag1[d1] = diag2[d2] = true;
backtrack(row + 1);
cols[col] = diag1[d1] = diag2[d2] = false;
}
}
backtrack(0);
return count;
}
Key Insight
🔑 The Key Insight: The three boolean arrays (cols, diag1, diag2) give us O(1) constraint checking. Without them, we'd scan rows, columns, and diagonals every time — O(n) per placement, or O(n!) overall instead of O(n!). The boolean arrays transform constraint checking from O(n) to O(1).
📋 Edge Cases to Consider
N = 1: Single queen on a 1×1 board → 1 solution. No conflicts possible.
N = 2, 3: No solutions exist. That's correct — the constraints are impossible to satisfy.
N = 0: Edge case — empty board, 0 solutions. (Not typically in constraints.)
N up to 9: Standard Leetcode constraints — backtracking is fast enough.
Large N (N > 15): Backtracking becomes slow. Use bitmask optimization or heuristic algorithms (but this is beyond interview scope).
Sudoku is the ultimate constraint satisfaction puzzle. Fill a 9×9 grid so that each row, column, and 3×3 box contains digits 1-9 exactly once.
Note
🧩 Real-World Analogy: Think of Sudoku like a neighborhood with 9 apartment buildings arranged in a 3×3 block. Each building has 9 apartments (3×3). You're assigning parking permits (digits 1-9) to every apartment. Each permit number can appear at most once per row of apartment buildings, per column of apartment buildings, and per building. It's a three-dimensional constraint problem disguised as a 2D grid!
🔍 Real-Time Thinking — Backtracking with Bitmasks
"For the solver, I need to find an empty cell, try digits 1-9, check if valid, and recurse. But scanning the whole board for each digit is O(9×9×9). What if I pre-compute bitmasksfor each row, column, and box? Then validity check is just one bitwise AND:(rowMask & (1 << digit))."
Sudoku Solver Backtracking with Constraint Propagation
Valid Sudoku — One-Pass Check
example.js
function isValidSudoku(board) {
const rows = Array.from({ length: 9 }, () => new Set());
const cols = Array.from({ length: 9 }, () => new Set());
const boxes = Array.from({ length: 9 }, () => new Set());
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const val = board[r][c];
if (val === ".") continue;
const boxIdx = Math.floor(r / 3) * 3 + Math.floor(c / 3);
if (rows[r].has(val) || cols[c].has(val) || boxes[boxIdx].has(val)) {
return false;
}
rows[r].add(val);
cols[c].add(val);
boxes[boxIdx].add(val);
}
}
return true;
}
Sudoku Solver — Backtracking with Bitmask Optimization
example.js
function solveSudoku(board) {
// Pre-compute bitmasks for O(1) validation
const rows = new Array(9).fill(0);
const cols = new Array(9).fill(0);
const boxes = new Array(9).fill(0);
// Initialize: mark filled cells in bitmasks
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
if (board[r][c] !== ".") {
const val = 1 << (board[r][c] - "0");
const b = Math.floor(r / 3) * 3 + Math.floor(c / 3);
rows[r] |= val;
cols[c] |= val;
boxes[b] |= val;
}
}
}
function backtrack() {
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
if (board[r][c] !== ".") continue;
const b = Math.floor(r / 3) * 3 + Math.floor(c / 3);
for (let num = 1; num <= 9; num++) {
const bit = 1 << num;
// O(1) validity with bit masks!
if ((rows[r] & bit) || (cols[c] & bit) || (boxes[b] & bit)) continue;
// Place digit
board[r][c] = String(num);
rows[r] |= bit;
cols[c] |= bit;
boxes[b] |= bit;
if (backtrack()) return true;
// Backtrack
board[r][c] = ".";
rows[r] ^= bit;
cols[c] ^= bit;
boxes[b] ^= bit;
}
return false; // No valid digit for this cell
}
}
return true; // All cells filled
}
backtrack();
}
Key Insight
🔑 Bitmask Optimization: Using integers as bitmasks reduces validity checks from O(9) per cell to O(1). Each bit position represents a digit (1-9).rows[r] & (1 << num) tells us if that digit is already used in the row. This is MUCH faster than scanning arrays.
📋 Edge Cases to Consider
Empty board (all '.'): Should be solvable — many solutions exist. The solver fills the first valid one.
Invalid starting board: Problem guarantees the input board is a valid puzzle (unique solution, valid initial state).
Partially filled: The solver only fills '.' cells. Pre-filled cells are treated as fixed constraints.
Complete board: If no '.' cells, the function returns immediately — already solved.
Unsolvable board: The problem guarantees at least one solution, but our backtracking handles this by returning false.
These problems extend the grid traversal pattern. Instead of placing pieces, you'researching through the grid — moving a blank tile, walking a path of letters, or determining parity-based outcomes.
Sliding Puzzle — BFS on State Space
Problem: You have a 2×3 board with tiles 1-5 and one blank (0). Slide tiles adjacent to the blank. Find the minimum moves to reach the target state [[1,2,3],[4,5,0]].
Note
🧩 Real-World Analogy: Think of the 15-puzzle (or 6-puzzle here) as a Rubik's Cube in 2D. Each move swaps the blank with an adjacent tile. The entireboard state is a single node in a graph. You BFS through ALL possible board configurations until you find the target. Each move creates a new "neighbor" state.
BFS on State Space — Not on the Grid!
This is the KEY insight: You're not BFS-ing on the grid. You're BFS-ing on thestate space — each node is an entire board configuration. The neighbors of a state are all possible boards after one valid move.
example.js
function slidingPuzzle(board) {
const target = "123450";
const start = board.flat().join("");
// If already solved
if (start === target) return 0;
// All 6 possible blank positions (0-5) and their neighbors
const neighbors = {
0: [1, 3], 1: [0, 2, 4], 2: [1, 5],
3: [0, 4], 4: [1, 3, 5], 5: [2, 4]
};
// BFS on STATE SPACE — each node is a board string
const queue = [[start, 0]];
const visited = new Set([start]);
while (queue.length) {
const [state, moves] = queue.shift();
for (const next of getNextStates(state, neighbors)) {
if (next === target) return moves + 1;
if (!visited.has(next)) {
visited.add(next);
queue.push([next, moves + 1]);
}
}
}
return -1; // Unsolvable
}
function getNextStates(state, neighbors) {
const blankIdx = state.indexOf("0");
const results = [];
for (const neighbor of neighbors[blankIdx]) {
const arr = state.split("");
[arr[blankIdx], arr[neighbor]] = [arr[neighbor], arr[blankIdx]];
results.push(arr.join(""));
}
return results;
}
Key Insight
🔑 State Space BFS: The sliding puzzle is solved by treating each board configuration as a node in a graph. BFS finds the shortest path (minimum moves) to the target. This is NOT about moving on the grid — it's about transforming one state into another.
📋 Edge Cases for Sliding Puzzle
Already solved: The board is already in target state. Return 0 immediately.
Unsolvable configuration: Some permutations can never reach the target (parity inversion). Return -1.
Single row (2×3): The board is always 2×3 in the standard problem. No variations.
Large state space: 6! = 720 possible states — BFS is very fast. A* would be overkill.
Word Search — Backtracking on Grid
Word Search (Leetcode 79): Given an M×N grid of characters, find if a target word exists. You can move 4-directionally (up, down, left, right) and cannot reuse cells.
Word Search II (Leetcode 212): Given a list of words, find ALL words that exist on the board. Use a Trie for prefix matching.
example.js
// Word Search I — Simple backtracking
function exist(board, word) {
const rows = board.length, cols = board[0].length;
function dfs(r, c, idx) {
if (idx === word.length) return true;
if (r < 0 || r >= rows || c < 0 || c >= cols) return false;
if (board[r][c] !== word[idx]) return false;
// Mark visited
const temp = board[r][c];
board[r][c] = "#"; // Mark as visited
// Explore 4 directions
const found = dfs(r+1, c, idx+1) ||
dfs(r-1, c, idx+1) ||
dfs(r, c+1, idx+1) ||
dfs(r, c-1, idx+1);
// Restore
board[r][c] = temp;
return found;
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (dfs(r, c, 0)) return true;
}
}
return false;
}
// Word Search II — Trie optimization
function findWords(board, words) {
// Build a Trie from the word list
const root = {};
for (const word of words) {
let node = root;
for (const ch of word) {
if (!node[ch]) node[ch] = {};
node = node[ch];
}
node.word = word; // Mark end of word
}
const result = [];
const rows = board.length, cols = board[0].length;
function dfs(r, c, node) {
if (node.word) {
result.push(node.word);
node.word = null; // Avoid duplicates
}
const temp = board[r][c];
board[r][c] = "#"; // Mark visited
for (const [dr, dc] of [[0,1],[0,-1],[1,0],[-1,0]]) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols &&
board[nr][nc] !== "#" && node[board[nr][nc]]) {
dfs(nr, nc, node[board[nr][nc]]);
}
}
board[r][c] = temp; // Restore
}
// Start DFS from every cell
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (root[board[r][c]]) {
dfs(r, c, root[board[r][c]]);
}
}
}
return result;
}
Tip
⚡ Word Search II Optimization: The Trie prunes the search space dramatically. Instead of running a full DFS for each word, the Trie allows us to explore all words simultaneously — we stop exploring when no word in the dictionary shares the current prefix. This turns O(k × M × N × 4ᴸ) into O(M × N × 4ᴸ) but with aggressive pruning.
Chessboard Game — Parity & Pattern
Problem (Leetcode 1812): Determine the color of a square on a chessboard given its coordinate (e.g., "a1" is dark, "h8" is dark). This is a simple parity problem but tests your understanding of coordinate systems on boards.
example.js
function squareIsWhite(coordinates) {
// Column letter: a=0, b=1, c=2, d=3, e=4, f=5, g=6, h=7
// Row number: 1-indexed from bottom
// Color is dark if (col + row) % 2 === 0, white if odd
const col = coordinates.charCodeAt(0) - 97; // 'a' -> 0
const row = parseInt(coordinates[1]) - 1; // '1' -> 0
return (col + row) % 2 === 1;
}
The chessboard parity follows (col + row) % 2: if even → dark square; if odd → light square. This pattern appears in MANY board problems — parity is your friend!
Warning
⚠️ Common Mistake: Don't forget to restore the cell after backtracking! The # marker must be temporary — otherwise subsequent searches will see incorrect visited states. This is the #1 bug in backtracking on grids.
Q1: How do I detect a win in Tic-Tac-Toe efficiently? Don't scan the board. Maintain running row/col/diag scores. Player 1 adds +1, Player 2 adds -1. When any score reaches ±n, that player wins. O(1) per move!
Key Insight
Q2: What's the "encoding trick" in Game of Life? Use two bits per cell: bit 0 = old state, bit 1 = new state. Compute new state from old neighbors (read bit 0). Store new state in bit 1. Second pass shifts right to extract new state. This gives in-place transformation.
Key Insight
Q3: Why a queue for Snake Game? The snake's body is a FIFO structure: head enters (enqueue), tail leaves (dequeue). A queue perfectly models this. Use a Set for O(1) body collision detection. Remember: when eating, DON'T dequeue the tail.
Key Insight
Q4: What are the three guards for N-Queens? cols[col] — same column attack. diag1[row - col + n - 1] — main diagonal detection (NW-SE). The offset makes the index non-negative. diag2[row + col] — anti-diagonal detection (NE-SW). All three are boolean arrays → O(1) per check!
Key Insight
Q5: Bitmask vs Set for Sudoku validation? Both give O(1) checks. Bitmasks (integers with bit positions) use less memory and are slightly faster (bitwise AND). Sets are more readable. For interviews, either is fine — but bitmasks show advanced understanding.
Key Insight
Q6: What's "BFS on state space" vs "BFS on grid"? Grid BFS: Each cell is a node. Move 4-directionally. Used in Word Search, pathfinding. State Space BFS: Each entire configuration is a node. Used in Sliding Puzzle. Neighbors are all reachable configurations after one move.
Key Insight
Q7: How does Trie help Word Search II? Without Trie: run DFS for each word (O(k × 4ᴸ)). With Trie: run ONE shared DFS. The Trie tells us which prefixes are still viable — if no word in the dictionary starts with current prefix, we stop exploring. This prunes aggressively.
Key Insight
Q8: What are common backtracking pitfalls on grids? #1: Forgetting to restore the cell after recursion (the biggest one!). #2: Not checking bounds before accessing the grid. #3: Re-visiting the same cell (infinite loop) — always mark visited. #4: Not accounting for diagonal movement when the problem says "4-directional".
📝 Key Takeaways
Tic-Tac-Toe Design (Leetcode 348) — Use running row/col/diag scores for O(1) win detection. Player 1 = +1, Player 2 = -1.
Valid Tic-Tac-Toe (Leetcode 794) — X count is O count or O count + 1; both can't win; X-win has one extra, O-win has equal counts.
Game of Life (Leetcode 289) — The two-bit encoding trick: old=bit0, new=bit1. First pass writes new, second pass extracts.
Snake Game (Leetcode 353) — Queue for body (FIFO), Set for collision. Dequeue only when NOT eating.
Sudoku Validator (Leetcode 36) — One pass with rows/cols/boxes sets or bitmasks. O(1) per check.
Sudoku Solver (Leetcode 37) — Backtracking with bitmask optimization. Each empty cell tries digits until one fits.
Sliding Puzzle (Leetcode 773) — BFS on STATE SPACE. Each board string is a node. 6! = 720 states max.
Word Search (Leetcode 79) — Backtracking with visited markers. Restore cells after recursion.
Word Search II (Leetcode 212) — Trie + shared DFS. Prune when no word has the current prefix.
Chessboard Color (Leetcode 1812) — (col + row) % 2 tells the color. Parity is a board-game superpower.
Common thread — Every board problem is about indexing, constraints, and state transitions. Master these and you master the board!
Note
🔮 What's Next? You've conquered the board! Now dive into Card Games & Probabilityto learn about chance-based games, expected value, and probability trees!