Skip to problem
←

Game of Life

Medium 0 attempts

Conway's Game of Life is played on an m x n board where each cell is either alive (1) or dead (0). Every cell has up to eight neighbors — horizontally, vertically, and diagonally adjacent — and the whole board updates at once, following these rules:

  • A live cell with fewer than two live neighbors dies (underpopulation).
  • A live cell with two or three live neighbors survives.
  • A live cell with more than three live neighbors dies (overpopulation).
  • A dead cell with exactly three live neighbors comes alive (reproduction).

Given the board's current state, compute its next state in place. Every transition must use the original board state.

The board is finite: positions outside it are dead, and edges do not wrap around. Compute exactly one generation.

Function contract

board is a nonempty rectangular matrix of 0 (dead) and 1 (alive).

Output: Update board in place by exactly one simultaneous generation. Return values are ignored; the runner checks board.

Example 1

Input
board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
Output
[[0,0,0],[1,0,1],[0,1,1],[0,1,0]]

Example 2

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

To update in-place, encode transitions with extra states: 2 means alive → dead, 3 means dead → alive. Count live neighbors using original states (values 1 or 2), then do a final pass to map states back to 0/1.

javascript
function gameOfLife(board) {
  const m = board.length, n = board[0].length;
  const dirs = [-1, 0, 1];

  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      let live = 0;
      for (const di of dirs) {
        for (const dj of dirs) {
          if (di === 0 && dj === 0) continue;
          const ni = i + di, nj = j + dj;
          if (ni >= 0 && ni < m && nj >= 0 && nj < n) {
            if (board[ni][nj] === 1 || board[ni][nj] === 2) live++;
          }
        }
      }
      if (board[i][j] === 1 && (live < 2 || live > 3)) board[i][j] = 2;
      if (board[i][j] === 0 && live === 3) board[i][j] = 3;
    }
  }

  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (board[i][j] === 2) board[i][j] = 0;
      if (board[i][j] === 3) board[i][j] = 1;
    }
  }
}

Time: O(m × n) Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript