InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Game of Life

medium Original ↗ 00:00

Problem

You are given an m x n grid of cells, where each cell is either alive (1) or dead (0). Every cell interacts with its eight neighbors (horizontal, vertical, diagonal). The grid advances to its next generation by applying these rules to every cell simultaneously:

  1. A live cell with fewer than two live neighbors dies (underpopulation).
  2. A live cell with two or three live neighbors survives.
  3. A live cell with more than three live neighbors dies (overpopulation).
  4. A dead cell with exactly three live neighbors becomes alive (reproduction).

Update the board in place to its next state. Every cell’s next state must be computed from the current generation, so an already-updated cell must not influence its neighbors.

Follow-up: can you do it with O(1) extra space?

Examples

Example 1: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]][[0,0,0],[1,0,1],[0,1,1],[0,1,0]] The isolated live cells at the top die of underpopulation, while dead cells with exactly three live neighbors become alive.

Example 2: board = [[1,1],[1,0]][[1,1],[1,1]] Each live cell has exactly two live neighbors and survives; the dead corner has three live neighbors and is born.

Constraints

  • 1 <= m, n <= 25
  • board[i][j] is 0 or 1

The board is small, so any per-cell scan passes. The point of the exercise is the in-place / O(1)-space follow-up.

Think about it first

Hint 1 If you update cells directly as you scan left to right and top to bottom, a cell you already flipped feeds its new value to its unprocessed neighbors. That violates the simultaneity rule.
Hint 2 Each cell needs only two facts: its old state and its new state. Can a single int hold both?
Hint 3 Use extra sentinel values: `2` means "was live, dies" and `3` means "was dead, becomes live". While counting neighbors, treat `2` as live and `3` as dead. A second pass decodes every cell back to `0`/`1`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug