A board of m rows and n columns models a colony of cells. Each cell is alive (1) or dead (0), and each has up to eight neighbours: the cells beside it, above, below and on the diagonals. Cells past the edge do not exist.
One round later, a live cell stays alive only if it has 2 or 3 live neighbours; with fewer it dies of loneliness, with more it dies of crowding. A dead cell comes alive if it has exactly 3 live neighbours. All cells change at the same moment, based on the board as it was.
Update board in place to show the next round. Return nothing.
Example 1
Input: board = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] Output: [[0, 0, 0], [1, 1, 1], [0, 0, 0]] Why: the ends of the bar die; the middle row's side cells are born
2 more examples and the constraints
Example 2
Input: board = [[1, 1], [1, 1]] Output: [[1, 1], [1, 1]] Why: every live cell has exactly 3 live neighbours
Example 3
Input: board = [[1, 1, 0], [1, 0, 0]] Output: [[1, 1, 0], [1, 1, 0]] Why: the empty corner of the L has 3 live neighbours
Constraints
- 1 ≤ m, n ≤ 25
- Every
board[i][j]is 0 or 1
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Copy the board firstO(m·n)
- Two states in one cellO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 25 × 25 board | Verdict |
|---|---|---|---|
| Copy the board first | O(m·n) | Simple; needs a second board | |
| Two states in one cell | O(m·n) | Best; in place, O(1) extra space |
m = rows, n = columns. Both do the same counting; they differ in memory.
Edge cases to test
- A single cell. It has no neighbours, so a live cell dies and a dead one stays dead.
- One row or one column. Neighbours exist on two sides at most; the bounds checks must clip the 3 × 3 window.
- A full board. Every cell is alive; only the corners (3 neighbours each) survive in a 3 × 3 board.
- Still life. A 2 × 2 block comes out exactly as it went in.
Common mistakes
- Updating cells in the same board without a copy or encoding, so later cells count new values.
- Counting the cell itself as one of its own neighbours.
- Reading neighbours as plain values after encoding, so a 2 (dead now) counts as alive.
How to talk through it
- 1Clarify. Do cells past the edge count as dead? Must I update in place? Do diagonals count?
- 2Name the trap. All cells change at once, so a cell must not see a neighbour's new value.
- 3Start simple. Copy the board and read only from the copy. O(m·n) time and space.
- 4Go in place. Store the next state in bit 1, read the old state with
& 1, then shift every cell right. - 5Test out loud. Run the vertical bar: it should turn sideways. Then a 2 × 2 block, which must not change.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?