Loading...
Learn Design Tic Tac Toe — a key concept for LLD interviews.
You're building a Tic-Tac-Toe game. The board is a 3x3 grid where players place X or O. You need to efficiently check if a cell is empty, place a mark, and detect winners.
enum Mark { EMPTY, X, O }
class Board {
private grid: Mark[][] = [
[Mark.EMPTY, Mark.EMPTY, Mark.EMPTY],
[Mark.EMPTY, Mark.EMPTY, Mark.EMPTY],
[Mark.EMPTY, Mark.EMPTY, Mark.EMPTY],
]
// O(1) win detection tracking
private rowCounts: number[][] = [[0,0],[0,0],[0,0]] // [row][X=0,O=1]
private colCounts: number[][] = [[0,0],[0,0],[0,0]]
private diagCounts: number[] = [0, 0] // main diag
private antiDiagCounts: number[] = [0, 0]
private moveCount: number = 0
placeMark(row: number, col: number, mark: Mark): boolean {
if (this.grid[row][col] !== Mark.EMPTY) return false
this.grid[row][col] = mark
this.moveCount++
// Update counts for O(1) win check
return true
}
}What's the best way to represent the 3x3 board?