15% off all plans & roadmaps Use code
See plansGame of Life
- LeetCode 289
- Medium
- Array/Matrix Manipulation Patterns
- Set Matrix Zeroes (In-place Marking)
Updated
TL;DR: Each cell's next state depends on the old states of its eight neighbors, so an update must not change what later cells read. Store each next state in a spare bit of the same cell, so one board holds two generations at once.
Problem
The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970.
The board is an m x n grid of cells. Each cell starts in one of two states: live (1) or dead (0). Every cell interacts with its eight neighbors (horizontal, vertical and diagonal) under four rules:
- Any live cell with fewer than two live neighbors dies, as if caused by under-population.
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by over-population.
- Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The next state comes from applying these rules to every cell at once. Births and deaths happen simultaneously. Given the current state board, return the next state.
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,1],[1,0]] Output: [[1,1],[1,1]]
Constraints
m == board.lengthn == board[i].length1 <= m, n <= 25board[i][j]is0or1.
Constraints that matter
- Each cell holds only 0 or 1, so the higher bits of every integer are free. That spare room lets you store the next state beside the current one.
- The grid is at most 25 by 25, so an O(m * n * 8) scan runs instantly. The real requirement is the simultaneous update, which decides how you store state.
- Cells on the border have fewer than eight neighbors, so every neighbor lookup needs a bounds check.
- A cell's rule uses only its own state and its neighbor count. You never need the full history of the board.
Hints
Hint 1
The rule for each cell depends on the old states of its neighbors.
Hint 2
The first version most people write counts neighbors and writes each result straight back.
Solution
Intuition
The rule for each cell depends on the old states of its neighbors. If you overwrite a cell with its next state too early, every later neighbor count reads a mix of old and new values. The board has to hold two generations at once.
Picture a row of mailboxes where the front slot is bit 0 and the back slot is bit 1. Neighbors read only front slots, new messages go in back slots, and a final sweep moves each back message forward.
This is the in-place marking pattern. The board already stores a value for each cell, and that value only needs one bit. Keep the current state in bit 0 and write the next state into bit 1. Reads use only bit 0, so a cell updated early never changes a later count.
Writing into bit 1 never touches bit 0, and reading value & 1 always gives the old state. After one full scan, a shift moves each next state down into bit 0. One pass counts and marks, and a second pass decodes.
Worked example
Input: board = [[1,1],[1,0]] Output: [[1,1],[1,1]] Explanation: The board is a 2 by 2 block with one dead corner. Each of the three live cells has two live neighbors, so each survives. The dead corner has exactly three live neighbors, so it becomes live. Every cell ends up live.
Approach 1: Brute force with a board copy
The first version most people write counts neighbors and writes each result straight back. That fails because a cell written early changes the count for a neighbor visited later. Copy the board first, so every count reads an untouched old generation while the real board takes the writes. This is correct, but it costs a second full board.
Steps
- Copy the board into
old, row by row, sooldholds the current generation. - For each cell (r, c), count the live cells among its up to eight neighbors in
old, skipping positions outside the grid. - If the cell is live in
oldand has two or three live neighbors, write 1 intoboard[r][c]. - If the cell is dead in
oldand has exactly three live neighbors, write 1 intoboard[r][c]. - Otherwise write 0 into
board[r][c]. - Stop.
boardnow holds the next generation, and nothing is returned.
Dry run
Start with old = [[1,1],[1,0]]. Every count below reads from old, never from board.
- Cell (0,0) is live. Its neighbors are (0,1)=1, (1,0)=1 and (1,1)=0, so the count is 2. Live with 2 stays live, so write 1.
- Cell (0,1) is live. Its neighbors are (0,0)=1, (1,0)=1 and (1,1)=0, so the count is 2. Write 1.
- Cell (1,0) is live. Its neighbors are (0,0)=1, (0,1)=1 and (1,1)=0, so the count is 2. Write 1.
- Cell (1,1) is dead. Its neighbors are (0,0)=1, (0,1)=1 and (1,0)=1, so the count is 3. Dead with 3 becomes live, so write 1.
The board is now [[1,1],[1,1]], which matches the expected output.
Complexity
| Time | O(m * n) |
|---|---|
| Space | O(m * n) |
Let m and n be the grid dimensions, so the grid has m * n cells. The two outer loops visit each cell once, and the inner loops check at most eight neighbors, so the scan does at most 8 * m * n neighbor reads. The copy writes m * n values once. Time is O(m * n), and the extra copy takes O(m * n) space.
PythonTested in our runner
from typing import List, Optional
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
m = len(board)
n = len(board[0])
# Copy the board so every neighbor count reads the old generation.
old = [row[:] for row in board]
for r in range(m):
for c in range(n):
live = 0
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if dr == 0 and dc == 0:
continue
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n:
live += old[nr][nc]
if old[r][c] == 1:
board[r][c] = 1 if live in (2, 3) else 0
else:
board[r][c] = 1 if live == 3 else 0JavaTested in our runner
class Solution {
public void gameOfLife(int[][] board) {
int m = board.length;
int n = board[0].length;
// Copy the board so every neighbor count reads the old generation.
int[][] old = new int[m][];
for (int r = 0; r < m; r++) {
old[r] = board[r].clone();
}
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
int live = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
if (dr == 0 && dc == 0) continue;
int nr = r + dr;
int nc = c + dc;
if (nr >= 0 && nr < m && nc >= 0 && nc < n) {
live += old[nr][nc];
}
}
}
if (old[r][c] == 1) {
board[r][c] = (live == 2 || live == 3) ? 1 : 0;
} else {
board[r][c] = (live == 3) ? 1 : 0;
}
}
}
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int m = board.size();
int n = board[0].size();
// Copy the board so every neighbor count reads the old generation.
vector<vector<int>> old = board;
for (int r = 0; r < m; ++r) {
for (int c = 0; c < n; ++c) {
int live = 0;
for (int dr = -1; dr <= 1; ++dr) {
for (int dc = -1; dc <= 1; ++dc) {
if (dr == 0 && dc == 0) continue;
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < m && nc >= 0 && nc < n) live += old[nr][nc];
}
}
if (old[r][c] == 1) board[r][c] = (live == 2 || live == 3) ? 1 : 0;
else board[r][c] = (live == 3) ? 1 : 0;
}
}
}
};JavaScriptTested in our runner
var gameOfLife = function(board) {
const m = board.length;
const n = board[0].length;
// Copy the board so every neighbor count reads the old generation.
const old = board.map(row => row.slice());
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
let live = 0;
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
if (dr === 0 && dc === 0) continue;
const nr = r + dr;
const nc = c + dc;
if (nr >= 0 && nr < m && nc >= 0 && nc < n) live += old[nr][nc];
}
}
if (old[r][c] === 1) board[r][c] = (live === 2 || live === 3) ? 1 : 0;
else board[r][c] = live === 3 ? 1 : 0;
}
}
};GoTested in our runner
func gameOfLife(board [][]int) {
m := len(board)
n := len(board[0])
// Copy the board so every neighbor count reads the old generation.
old := make([][]int, m)
for r := 0; r < m; r++ {
old[r] = make([]int, n)
copy(old[r], board[r])
}
for r := 0; r < m; r++ {
for c := 0; c < n; c++ {
live := 0
for dr := -1; dr <= 1; dr++ {
for dc := -1; dc <= 1; dc++ {
if dr == 0 && dc == 0 {
continue
}
nr, nc := r+dr, c+dc
if nr >= 0 && nr < m && nc >= 0 && nc < n {
live += old[nr][nc]
}
}
}
if old[r][c] == 1 {
board[r][c] = 0
if live == 2 || live == 3 {
board[r][c] = 1
}
} else {
board[r][c] = 0
if live == 3 {
board[r][c] = 1
}
}
}
}
}C#Tested in our runner
public class Solution {
public void gameOfLife(int[][] board) {
int m = board.Length;
int n = board[0].Length;
// Copy the board so every neighbor count reads the old generation.
int[][] old = new int[m][];
for (int r = 0; r < m; r++) {
old[r] = (int[])board[r].Clone();
}
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
int live = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
if (dr == 0 && dc == 0) continue;
int nr = r + dr;
int nc = c + dc;
if (nr >= 0 && nr < m && nc >= 0 && nc < n) {
live += old[nr][nc];
}
}
}
if (old[r][c] == 1) {
board[r][c] = (live == 2 || live == 3) ? 1 : 0;
} else {
board[r][c] = (live == 3) ? 1 : 0;
}
}
}
}
}The Set Matrix Zeroes (In-place Marking) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Set Matrix Zeroes (In-place Marking)
Approach 2: One-pass bit marking, then shiftOptimalSet Matrix Zeroes (In-place Marking)
The copy wastes m * n cells on memory that only remembers the old generation. Each cell already has a spare bit, because its value is only 0 or 1. Write the next state into bit 1 during the scan. Count neighbors by reading only bit 0, which still holds the old state for every cell. A final shift moves each next state into bit 0.
Steps
- Visit every cell (r, c) in row-major order.
- For each of the eight neighbors inside the grid, add
board[nr][nc] & 1tolive. This reads the old state. - Read the cell's own old state with
board[r][c] & 1intoalive. - If
liveis 3, oraliveis 1 andliveis 2, set bit 1 withboard[r][c] |= 2. - After every cell is visited, run a second pass and set
board[r][c] >>= 1for each cell. - Stop. Each cell holds 0 or 1, and the board holds the next generation.
Dry run
Start with board = [[1,1],[1,0]]. The table shows each cell's live-neighbor count (from bit 0 only), its old state, the next state written into bit 1, and the board after that step.
| Step | Cell | Live neighbors | Old state | Next state | Board after |
|---|---|---|---|---|---|
| 0 | start | [[1,1],[1,0]] | |||
| 1 | (0,0) | 2 | 1 | 1, survives | [[3,1],[1,0]] |
| 2 | (0,1) | 2 | 1 | 1, survives | [[3,3],[1,0]] |
| 3 | (1,0) | 2 | 1 | 1, survives | [[3,3],[3,0]] |
| 4 | (1,1) | 3 | 0 | 1, born | [[3,3],[3,2]] |
| 5 | shift pass | [[1,1],[1,1]] |
Step 2 counts the cell (0,0) as live even though its value is now 3. That works because the count reads bit 0, and setting bit 1 leaves bit 0 unchanged. The shift in step 5 turns 3 into 1 and 2 into 1, which gives the expected output.
Complexity
| Time | O(m * n) |
|---|---|
| Space | O(1) |
Let m and n be the grid dimensions, so the grid has m * n cells. The first pass visits each cell once and checks at most eight neighbors, which is at most 8 * m * n neighbor reads. The second pass visits each cell once more, so the total is at most 9 * m * n operations. The algorithm stores only a few loop variables, and the marking lives in cells that already exist, so the extra space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
m = len(board)
n = len(board[0])
for r in range(m):
for c in range(n):
live = 0
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if dr == 0 and dc == 0:
continue
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n:
# bit 0 holds the current state
live += board[nr][nc] & 1
alive = board[r][c] & 1
# bit 1 stores the next state
if live == 3 or (alive == 1 and live == 2):
board[r][c] |= 2
for r in range(m):
for c in range(n):
board[r][c] >>= 1JavaTested in our runner
class Solution {
public void gameOfLife(int[][] board) {
int m = board.length;
int n = board[0].length;
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
int live = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
if (dr == 0 && dc == 0) continue;
int nr = r + dr;
int nc = c + dc;
if (nr >= 0 && nr < m && nc >= 0 && nc < n) {
live += board[nr][nc] & 1;
}
}
}
int alive = board[r][c] & 1;
// bit 1 stores the next state
if (live == 3 || (alive == 1 && live == 2)) {
board[r][c] |= 2;
}
}
}
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
board[r][c] >>= 1;
}
}
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int m = board.size();
int n = board[0].size();
for (int r = 0; r < m; ++r) {
for (int c = 0; c < n; ++c) {
int live = 0;
for (int dr = -1; dr <= 1; ++dr) {
for (int dc = -1; dc <= 1; ++dc) {
if (dr == 0 && dc == 0) continue;
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < m && nc >= 0 && nc < n) live += board[nr][nc] & 1;
}
}
int alive = board[r][c] & 1;
// bit 1 stores the next state
if (live == 3 || (alive == 1 && live == 2)) board[r][c] |= 2;
}
}
for (int r = 0; r < m; ++r)
for (int c = 0; c < n; ++c)
board[r][c] >>= 1;
}
};JavaScriptTested in our runner
var gameOfLife = function(board) {
const m = board.length;
const n = board[0].length;
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
let live = 0;
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
if (dr === 0 && dc === 0) continue;
const nr = r + dr;
const nc = c + dc;
if (nr >= 0 && nr < m && nc >= 0 && nc < n) live += board[nr][nc] & 1;
}
}
const alive = board[r][c] & 1;
// bit 1 stores the next state
if (live === 3 || (alive === 1 && live === 2)) board[r][c] |= 2;
}
}
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
board[r][c] >>= 1;
}
}
};GoTested in our runner
func gameOfLife(board [][]int) {
m := len(board)
n := len(board[0])
for r := 0; r < m; r++ {
for c := 0; c < n; c++ {
live := 0
for dr := -1; dr <= 1; dr++ {
for dc := -1; dc <= 1; dc++ {
if dr == 0 && dc == 0 {
continue
}
nr, nc := r+dr, c+dc
if nr >= 0 && nr < m && nc >= 0 && nc < n {
live += board[nr][nc] & 1
}
}
}
alive := board[r][c] & 1
// bit 1 stores the next state
if live == 3 || (alive == 1 && live == 2) {
board[r][c] |= 2
}
}
}
for r := 0; r < m; r++ {
for c := 0; c < n; c++ {
board[r][c] >>= 1
}
}
}C#Tested in our runner
public class Solution {
public void gameOfLife(int[][] board) {
int m = board.Length;
int n = board[0].Length;
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
int live = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
if (dr == 0 && dc == 0) continue;
int nr = r + dr;
int nc = c + dc;
if (nr >= 0 && nr < m && nc >= 0 && nc < n) {
live += board[nr][nc] & 1;
}
}
}
int alive = board[r][c] & 1;
// bit 1 stores the next state
if (live == 3 || (alive == 1 && live == 2)) {
board[r][c] |= 2;
}
}
}
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
board[r][c] >>= 1;
}
}
}
}Common mistakes
- Writing
board[r][c] = 0orboard[r][c] = 1inside the first scan. Later neighbors then read the new generation. Write only the next-state bit with|= 2during the scan, and shift in a second pass. - Testing
board[nr][nc] == 1inside the neighbor loop. After a neighbor gets bit 1 set, its value becomes 2 or 3, and the equality test misses it. Read the old state with& 1. - Running
board[r][c] >>= 1inside the scan. That decodes a cell before its neighbors read it. Keep all shifting in the second pass. - Counting the cell itself. Without a skip for
dr == 0 and dc == 0, every cell counts itself as a neighbor and every rule shifts. Skip the center of the 3 by 3 window. - Missing the bounds check, or writing a check that lets -1 through. Most languages throw an index error, and Python silently reads the last row because
board[-1]is valid. Test0 <= nr < mand0 <= nc < n. - Applying the survival rule to dead cells. Writing
live == 2 or live == 3for a dead cell brings it to life with only two neighbors. A dead cell needs exactly three live neighbors.
Edge cases
[[0]]: a single dead cell with no neighbors stays[[0]].[[1]]: a lone live cell has zero neighbors, so it dies from under-population and returns[[0]].[[1,1,1]]: the two ends have one live neighbor and die, the middle has two and lives, so the output is[[0,1,0]].[[1],[1],[1]]: a single column behaves the same way, and the output is[[0],[1],[0]].[[1,1],[1,1]]: every cell has three live neighbors, so the block is stable and the output is unchanged.- A 25 by 25 grid of zeros: no dead cell has three live neighbors, so the output is all zeros, and the bounds checks keep every index in range.
Follow-ups interviewers ask
- Can you update the board in place while keeping the update simultaneous?
- Yes. Store each cell's next state in bit 1 and keep its current state in bit 0. Every neighbor count reads only bit 0, so a cell updated early never changes a later count. A final shift moves the next states into bit 0.
- What if the board were infinite, and live cells can reach the border?
- Stop storing the whole grid, and keep a set of live cell coordinates instead. For each generation, add one to a hash map entry for every neighbor of every live cell. The next live set is the cells with count 3, plus the live cells with count 2. The work depends on the number of live cells, not the grid size, and no border exists.
- What if the grid is too large to hold in memory?
- Process the grid as a stream of rows. The next state of row r depends only on rows r - 1, r and r + 1. Keep a copy of the original previous row, and read the next row before you write the current one. Memory then holds a few rows, not the whole grid.
Game of Life FAQ
What is the time complexity of Game of Life?
It is O(m * n), where m and n are the board dimensions. Each cell is visited a constant number of times and checks at most eight neighbors. The copy version and the in-place version share this time bound.
Why use in-place bit marking for Game of Life?
Each cell holds only 0 or 1, so it has spare bits. Writing the next state into bit 1 keeps both generations in one array. Reads use only bit 0, which keeps the update simultaneous.
Can Game of Life be solved in O(1) extra space?
Yes. The in-place solution uses only a few integer variables beyond the input board. The board copy version needs O(m * n) extra space, which the in-place version removes.
Why does Game of Life need two passes?
The first pass sets bit 1 for every cell, and bit 0 still holds the old state for every neighbor. The second pass shifts each value right by one, which turns next states into current states. Shifting during the first pass would change values that later cells still need.
Does the Python version of Game of Life return a new board?
No. The method changes the list of lists that is passed in and returns None. Python lists are references, so the writes show up in the caller's board.
Asked at
See which companies ask this — Pro
Related problems
- Set Matrix Zeroes · same technique: Set Matrix Zeroes (In-place Marking)
- Diagonal Traverse · same technique: Set Matrix Zeroes (In-place Marking)
- First Missing Positive · next harder, same pattern
- Longest Substring Without Repeating Characters · same pattern: Array/Matrix Manipulation Patterns
- Group Anagrams · same pattern: Array/Matrix Manipulation Patterns
- Longest Consecutive Sequence · same pattern: Array/Matrix Manipulation Patterns
- Top K Frequent Elements · same pattern: Array/Matrix Manipulation Patterns
- Task Scheduler · same pattern: Array/Matrix Manipulation Patterns
- Product of Array Except Self · same pattern: Array/Matrix Manipulation Patterns
- Spiral Matrix · same pattern: Array/Matrix Manipulation Patterns