InterviewPrepKit

Home / Coding / Arrays & Hashing

Game of Life

medium Original ↗
Solving tips
  • The simultaneity rule means you must count neighbors from the CURRENT generation, so you cannot overwrite cells naively in place.
  • For O(1) space, encode both old and new state in one int with sentinels (2 = live->dead, 3 = dead->live), treat 1 and 2 as 'was live' while counting, then decode in a second pass.
  • Check all 8 neighbors with bounds checks in both dimensions and skip the cell itself (dr==dc==0).
  • Target O(m*n) time and O(1) extra space; the copy-the-board approach is O(m*n) space and misses the follow-up.

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. “Simultaneously” is the catch: every cell’s next state must be computed from the current generation, so you cannot let an already-updated cell 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 lone live cells at the top die of underpopulation while dead cells adjacent to three live ones spring to life.

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 tiny, so any per-cell scan passes — the real constraint is the in-place / O(1) space follow-up.

Think about it first

Hint 1 If you update cells left to right and top to bottom directly, a cell you already flipped will feed the *new* value to its unprocessed neighbors. Why is that wrong here?
Hint 2 You only ever need two facts per cell: what it *was* and what it *will be*. A cell is an int — can one int carry both facts at once?
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`.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.