KatInterview

Build a Dropping Tile Game with Win Detection

Data Structure DesignModel answer
MediumModel answerData Structure Designgame-logic2d-gridstate-machine

Last updated

Implement game logic for a gravity-based two-player board game: handle piece placement, detect wins efficiently, and analyze complexity.

You're building a two-player board game where pieces drop into columns and stack vertically due to gravity. Design and implement the core game engine.

Rules

  • The board has R rows and C columns (default 6×7)
  • Two players alternate turns, dropping circular pieces into columns
  • Pieces fall to the lowest available position in the chosen column
  • A player wins by forming a continuous line of K pieces (default K=4) in any direction: horizontal, vertical, or diagonal
  • The game ends in a draw when the board fills completely with no winner

Requirements

Implement a game class that supports:

  1. Piece placement: Accept a column number and place the current player's piece
  2. Move validation: Reject invalid moves (full columns, out of bounds, wrong turn, game already finished)
  3. Win detection: Determine if the last move created a winning line
  4. Game state: Track whose turn it is and whether the game is ongoing, won, or drawn

Make the board dimensions and win-length configurable.

What to discuss

  • Time and space complexity of each operation
  • How your win-checking algorithm avoids scanning the entire board
  • Edge cases and error handling
  • Possible extensions (AI player, multiplayer service, different board shapes)

Hints

Hint 1

Track the fill level of each column to avoid scanning for empty cells

Hint 2

A newly formed winning line must pass through the piece that was just placed

Hint 3

Count matching pieces in both directions along each line type (horizontal, vertical, two diagonals)