LeetCode #289 Medium

Game of Life

Game of Life is LeetCode 289 (Medium). It asks for one step of Conway's Game of Life. The board is an m × n grid where 1 is a live cell and 0 is a dead one. Each cell has up to eight neighbours: left, right, up, down and the four diagonals.

  • A live cell with 2 or 3 live neighbours stays live; with fewer or more, it dies.
  • A dead cell with exactly 3 live neighbours becomes live.

All cells change at the same moment, so every rule reads the board as it was before the step. Update board in place; the function returns nothing.

Constraints
  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 25
  • board[i][j] is 0 or 1.
arraymatrixsimulation
Open on LeetCode ↗
02

Intuition

The trap is order. If you overwrite a cell and then count it as a neighbour of the next cell, that count sees the new board, not the old one.

The fix is to let each cell hold both states at once. Bit 0 keeps the current state and bit 1 records the next one. Counting reads only bit 0 (cell & 1), and no write in the first pass touches bit 0, so every count comes from the old board. When every cell has been decided, shifting each value right by one moves the next state into bit 0. The board itself is the scratch space, so no copy is needed.

How to spot this pattern

"Update every cell at once, in place" means the old and new values must live side by side. When a cell holds 0 or 1, the spare bits of the integer are free storage.

03

Approach

Try it first

Before reading on, write the rules as one test: when is a cell live in the next state? Then decide what number to store in a cell that is live now but dies, and in one that is dead now but is born, so that a neighbour can still read the old state.

1

Count live neighbours from bit 0

For cell (r, c), visit every cell in the 3 × 3 block around it except itself, and add board[nr][nc] & 1. Clamp the block with max and min so cells on the border only look inside the grid.

2

Decide the next state with one test

The cell is live next time if it has exactly 3 live neighbours, or exactly 2 and is live now. Those are the only two ways to end live, so every other case ends dead and needs no write.

3

Store the next state in bit 1

When the cell will be live, do board[r][c] |= 2. That sets bit 1 and leaves bit 0 alone, so cells checked later still read this cell's old state.

4

Shift every cell to finish

In a second pass, do board[r][c] >>= 1. A 3 or a 2 becomes 1 (live next), and a 1 or a 0 becomes 0 (dead next). It has to be a separate pass: shifting during the first pass would erase bit 0 before every neighbour had read it.

04

Code in Python, C++ and Java

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def gameOfLife(self, board: List[List[int]]) -> None:
▶6 rows, cols = len(board), len(board[0])
▶7 for r in range(rows):
▶8 for c in range(cols):
▶9 live = 0
▶10 for nr in range(max(r - 1, 0), min(r + 2, rows)):
▶11 for nc in range(max(c - 1, 0), min(c + 2, cols)):
▶12 if (nr, nc) != (r, c):
▶13 live += board[nr][nc] & 1
▶14 if live == 3 or (live == 2 and board[r][c] & 1):
▶15 board[r][c] |= 2
▶16 for r in range(rows):
▶17 for c in range(cols):
▶18 board[r][c] >>= 1
board010001111000cellneighboursnow→nextstored value1 is live, 0 is dead; decide cell by cell
rows4
cols3
Every cell will be judged on the board as it is now. While deciding, a cell keeps its current state in bit 0 and gets its next state in bit 1, so the numbers can grow to 2 or 3 until the final shift.
board010001111000row 0, col 01neighboursdeadnow→deadnext0 → 0stored valuerow 0, col 0: 1 live neighbour → stays dead
cell(0, 0)
live1
stored0
It is dead with 1 live neighbour. Only exactly 3 brings a dead cell to life, so nothing is written.
board010001111000row 0, col 11neighbourslivenow→deadnext1 → 1stored valuerow 0, col 1: 1 live neighbour → dies
cell(0, 1)
live1
stored1
It is live with 1 live neighbour, too few to survive. Nothing is written, so bit 0 still says live, and cells checked later count it as live, which is right for this step.
board010001111000row 0, col 22neighboursdeadnow→deadnext0 → 0stored valuerow 0, col 2: 2 live neighbours → stays dead
cell(0, 2)
live2
stored0
It is dead with 2 live neighbours. Only exactly 3 brings a dead cell to life, so nothing is written.
board010201111000row 1, col 03neighboursdeadnow→livenext0 → 2stored valuerow 1, col 0: 3 live neighbours → born
cell(1, 0)
live3
stored2
It is dead with exactly 3 live neighbours, so it is born. Bit 1 is set and it is stored as 2. Bit 0 is still 0, so later cells do not count it yet.
board010201111000row 1, col 15neighboursdeadnow→deadnext0 → 0stored valuerow 1, col 1: 5 live neighbours → stays dead
cell(1, 1)
live5
stored0
It is dead with 5 live neighbours. Only exactly 3 brings a dead cell to life, so nothing is written.
board010203111000row 1, col 23neighbourslivenow→livenext1 → 3stored valuerow 1, col 2: 3 live neighbours → stays live
cell(1, 2)
live3
stored3
It is live with 3 live neighbours, and 2 or 3 keeps a live cell alive. Bit 1 is set, so it is stored as 3: bit 0 still says live for the cells checked after it.
board010203111000row 2, col 01neighbourslivenow→deadnext1 → 1stored valuerow 2, col 0: 1 live neighbour → dies
cell(2, 0)
live1
stored1
It is live with 1 live neighbour, too few to survive. Nothing is written, so bit 0 still says live, and cells checked later count it as live, which is right for this step.
board010203131000row 2, col 13neighbourslivenow→livenext1 → 3stored valuerow 2, col 1: 3 live neighbours → stays live
cell(2, 1)
live3
stored3
It is live with 3 live neighbours, and 2 or 3 keeps a live cell alive. Bit 1 is set, so it is stored as 3: bit 0 still says live for the cells checked after it.
board010203133000row 2, col 22neighbourslivenow→livenext1 → 3stored valuerow 2, col 2: 2 live neighbours → stays live
cell(2, 2)
live2
stored3
It is live with 2 live neighbours, and 2 or 3 keeps a live cell alive. Bit 1 is set, so it is stored as 3: bit 0 still says live for the cells checked after it.
board010203133000row 3, col 02neighboursdeadnow→deadnext0 → 0stored valuerow 3, col 0: 2 live neighbours → stays dead
cell(3, 0)
live2
stored0
It is dead with 2 live neighbours. Only exactly 3 brings a dead cell to life, so nothing is written.
board010203133020row 3, col 13neighboursdeadnow→livenext0 → 2stored valuerow 3, col 1: 3 live neighbours → born
cell(3, 1)
live3
stored2
It is dead with exactly 3 live neighbours, so it is born. Bit 1 is set and it is stored as 2. Bit 0 is still 0, so later cells do not count it yet.
board010203133020row 3, col 22neighboursdeadnow→deadnext0 → 0stored valuerow 3, col 2: 2 live neighbours → stays dead
cell(3, 2)
live2
stored0
It is dead with 2 live neighbours. Only exactly 3 brings a dead cell to life, so nothing is written.
board000101011010every cell shifts right3 → 1live, stays2 → 1born1 → 0dies0 → 0stays deadshift every cell → the next state is in place
board[[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
Every cell is decided, so no one needs the old state any more. Shifting right by one drops bit 0 and moves bit 1 down: 3 and 2 become 1, while 1 and 0 become 0. The board now shows the next generation.
05

Copy the board first

old is a snapshot of the board before any change. Every count reads old, so writing the new value into board straight away is safe. It is the easiest version to get right, at the cost of a second grid.

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def gameOfLife(self, board: List[List[int]]) -> None:
▶6 rows, cols = len(board), len(board[0])
▶7 old = [row[:] for row in board]
▶8 for r in range(rows):
▶9 for c in range(cols):
▶10 live = sum(
▶11 old[nr][nc]
▶12 for nr in range(max(r - 1, 0), min(r + 2, rows))
▶13 for nc in range(max(c - 1, 0), min(c + 2, cols))
▶14 if (nr, nc) != (r, c)
▶15 )
▶16 board[r][c] = 1 if live == 3 or (live == 2 and old[r][c]) else 0
06

Common pitfalls

Writing the new state straight into the cell

✗ Wrong
board[r][c] = 1 if live == 3 or (live == 2 and board[r][c]) else 0
✓ Right
if live == 3 or (live == 2 and board[r][c] & 1):
    board[r][c] |= 2

Cells checked later count the new value instead of the old one. On the vertical line [[0,1,0],[0,1,0],[0,1,0]] the top cell dies first, so the cell below-left of it counts 2 neighbours instead of 3 and is never born. The result is an empty board; the right answer is the horizontal line [[0,0,0],[1,1,1],[0,0,0]].

Counting a neighbour without masking bit 0

✗ Wrong
live += board[nr][nc]
✓ Right
live += board[nr][nc] & 1

After marking, a cell that stays live holds 3 and a newborn holds 2, so unmasked they add too much. On [[1,1],[1,0]] the top-left cell is marked first and holds 3; the next two cells then count 4 and die, and the bottom-right cell counts 5 and is never born. The output is [[1,0],[0,0]] instead of [[1,1],[1,1]].

Counting the cell itself

✗ Wrong
for nr in range(max(r - 1, 0), min(r + 2, rows)):
    for nc in range(max(c - 1, 0), min(c + 2, cols)):
        live += board[nr][nc] & 1
✓ Right
        if (nr, nc) != (r, c):
            live += board[nr][nc] & 1

The 3 × 3 block includes the centre cell. In the square [[1,1],[1,1]] every cell has 3 live neighbours and should stay live, but with itself counted it sees 4 and dies, so the whole board comes out dead.

07

Edge cases

A single cell, [[1]]

The clamped block holds only the cell itself, which is skipped, so the count is 0 and the cell dies: [[0]].

08

Complexity

Time
O(m · n)
Space
O(1)
Each cell reads at most 8 neighbours in the first pass and is shifted once in the second. The only extra storage is a few counters, since the next state lives in bit 1 of each cell.
09

Game of Life FAQ

How would you handle an infinite board?

Stop storing a grid. Keep only the live cells as a set of (row, col) pairs. For each live cell, add 1 to a counter for each of its 8 neighbours. The next live set is every cell whose counter is 3, plus every live cell whose counter is 2. The work grows with the number of live cells, not with the size of the board, and there is no border to fall off.

Other solutions mark cells with −1 and 2. Is that different?

It is the same idea with different labels: one marker means "live now, dead next" and the other "dead now, live next". Counting must then treat one marker as live and the other as dead, and a final pass maps each marker to 0 or 1. The bit version needs no special cases: & 1 is the old state and >> 1 is the new one.