Game of Life
Medium
Topics
The board is an m x n grid of cells, each 1 (live) or 0 (dead). Every cell has up to eight neighbours — horizontal, vertical and diagonal.
Return the board after one step, where every cell updates simultaneously according to its live neighbour count:
- a live cell with fewer than 2 live neighbours dies;
- a live cell with 2 or 3 live neighbours lives on;
- a live cell with more than 3 live neighbours dies;
- a dead cell with exactly 3 live neighbours becomes live.
On this judge the rows of the returned board are shown separated by |.
Example 1
Input: grid = [[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]] Explanation: The cell at (3,1) has exactly three live neighbours above it and is born, while (0,1) has only one and dies.
Example 2
Input: grid = [[1,1],[1,0]] Output: [[1,1],[1,1]] Explanation: Each live cell has two live neighbours and survives, and the dead corner has three and is born.
Example 3
Input: grid = [[0,0],[0,0]] Output: [[0,0],[0,0]] Explanation: An empty board stays empty — nothing has three neighbours.
Constraints
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 25
- grid[i][j] is 0 or 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
The word doing all the work is simultaneously. Every cell’s new value depends on the board as it was before the step, so writing a new value into a cell before its neighbours have been read corrupts their counts.
The straightforward fix is a second board: read from the old one, write to the new one, and nothing can interfere. That is the right first answer and it is what the code below does.
The in-place version is the reason this problem gets asked, and it is worth knowing the idea: a cell only needs to carry two bits, its old state and its new one. Encoding the new state in a higher bit lets one pass compute every cell while the low bit still holds the original board, and a second pass shifts the new state down. The neighbour count then reads the low bit and is unaffected by cells already decided.
Approach
- Allocate an output board of the same size.
- For each cell, count live neighbours by looking at the eight offsets around it in the input board, skipping anything off the edge.
- Apply the rules: a live cell survives on a count of 2 or 3; a dead cell is born on a count of exactly 3; everything else is dead.
- Write the result into the output board and return it.
Walkthrough
grid = [[0,1,0],
[0,0,1],
[1,1,1],
[0,0,0]]
cell state live neighbours becomes
(0,1) live 1 -- (1,2)? no, only (0,0)/(1,0)/(1,1)/(1,2)
of which (1,2) is live dies 0
(1,0) dead 3 -- (0,1) (2,0) (2,1) born 1
(1,2) live 2 -- (2,1) (2,2) lives 1
(2,1) live 3 -- (2,0) (2,2) (1,2) lives
but also (1,1) dead, (3,*) dead -> count 3 1
(3,1) dead 3 -- (2,0) (2,1) (2,2) born 1
Every count above is taken from the ORIGINAL board. Reading
(1,0) as live while counting (0,1) would be the bug this
problem exists to catch.Complexity
- Time — O(m * n): eight neighbour reads per cell, a fixed cost.
- Space — O(m * n): the output board. The bit-encoding variant is O(1) beyond the input.
Common Pitfalls
- Updating the board in place without encoding. A cell that has already flipped feeds the wrong value into its neighbours’ counts, and the error spreads across the sweep.
- Counting only the four orthogonal neighbours. There are eight — the diagonals matter, and example 2 depends on one.
- Counting the cell itself. The offsets must exclude
(0, 0). - Running the rules more than once. The question asks for exactly one step.
Full Solution — all languages
class Solution:
def gameOfLife(self, grid):
NEIGHBOURS = ((-1, -1), (-1, 0), (-1, 1), (0, -1),
(0, 1), (1, -1), (1, 0), (1, 1))
rows, cols = len(grid), len(grid[0])
out = [[0] * cols for _ in range(rows)]
for r in range(rows):
for c in range(cols):
live = 0
for dr, dc in NEIGHBOURS:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
live += 1
if grid[r][c] == 1:
out[r][c] = 1 if live in (2, 3) else 0
else:
out[r][c] = 1 if live == 3 else 0
return outimport java.util.*;
class Solution {
public int[][] gameOfLife(int[][] grid) {
int[][] N = { {
-1, -1
},
{
-1, 0
},
{
-1, 1
},
{
0, -1
},
{
0, 1
},
{
1, -1
},
{
1, 0
},
{
1, 1
}
};
int rows = grid.length, cols = grid[0].length;
int[][] out = new int[rows][cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
int live = 0;
for (int[] d : N) {
int nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 1) live++;
}
if (grid[r][c] == 1) out[r][c] = (live == 2 || live == 3) ? 1 : 0;
else out[r][c] = (live == 3) ? 1 : 0;
}
}
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> gameOfLife(vector<vector<int>>& grid) {
int N[8][2] = { {
-1, -1
},
{
-1, 0
},
{
-1, 1
},
{
0, -1
},
{
0, 1
},
{
1, -1
},
{
1, 0
},
{
1, 1
}
};
int rows = grid.size(), cols = grid[0].size();
vector<vector<int>> out(rows, vector<int>(cols, 0));
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
int live = 0;
for (auto& d : N) {
int nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 1) live++;
}
if (grid[r][c] == 1) out[r][c] = (live == 2 || live == 3) ? 1 : 0;
else out[r][c] = (live == 3) ? 1 : 0;
}
}
return out;
}
};/**
* @param {number[][]} grid
* @return {number[][]}
*/ var gameOfLife = function(grid) {
const NEIGHBOURS = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
const rows = grid.length, cols = grid[0].length;
const out = Array.from({ length: rows }, () => new Array(cols).fill(0));
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
let live = 0;
for (const d of NEIGHBOURS) {
const nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] === 1) live++;
}
if (grid[r][c] === 1) out[r][c] = (live === 2 || live === 3) ? 1 : 0;
else out[r][c] = live === 3 ? 1 : 0;
}
}
return out;
};