Interview conceptCoding & Algorithms

Stateful Game Simulation And Board Modeling

Asked of: Software Engineer

Last updated

Editorial comparison table showing five stateful board-modeling patterns, their state representations, and the invariants or complexity rules that keep simulations correct.

What's being tested

These problems test stateful simulation: representing a mutable board or grid, applying legal moves in order, and detecting termination conditions efficiently. You must choose data structures that preserve invariants, handle boundaries and dynamic growth, and support operations such as undo/redo or shortest-path search without accidentally using stale state.

Patterns & templates

  • Bottom-insertion board — track each column’s next occupied position; insertion is O(1), while win checks scan only affected lines.

  • Directional win detection — from the latest move, count contiguous pieces in (dr, dc) and (-dr, -dc); test four axes, not every cell.

  • Unbounded grid modeling — use a hash map keyed by (row, column) for sparse boards; avoid allocating an enormous dense matrix.

  • Undo/redo state — store reversible moves or immutable snapshots; clear the redo stack after any new move following an undo.

  • Snake BFS — model (head position, body configuration) as state; use a queue and visited set, rejecting walls, bodies, and illegal time transitions.

  • State invariants — validate turn order, full-column moves, coordinates, collision rules, and whether a move after game-over is forbidden.

  • Complexity accounting — prefer O(k) win detection around one move over O(rows × columns) rescanning; state space may dominate BFS memory.

Common pitfalls

Pitfall: Checking only the newly placed piece’s row or column misses diagonal wins and runs extending on both sides.

Pitfall: Treating a board shift as merely changing a column height loses piece coordinates; update or model all affected state consistently.

Pitfall: Marking Snake cells visited by position alone can prune valid paths; include every state component that changes future legal moves.

Practice these

The practice cards below cover the canonical variants — solve all of them and time yourself.

Practice questions

Related concepts