Game of Life (LeetCode 289): Solution and Explanation
Every cell on an m x n board is live (1) or dead (0). Apply Conway's four rules to all cells at once, using each cell's eight neighbours from the current generation, and overwrite board with the next generation without returning anything.
Intuition
The rules themselves are easy: count the live neighbours, then a live cell survives with 2 or 3 and a dead cell is born with exactly 3. The difficulty is the word simultaneously. If you write the new value of cell (0,0) straight into the board, cell (0,1) will count that new value when it looks back at its neighbour, and the answer drifts.
The simple fix is to copy the board and read from the copy. That costs O(mn) extra memory, and the follow-up asks for in-place. The trick is to notice that a cell holds 0 or 1, which uses only the lowest bit of an integer. The next bit is free.
So during the scan, leave bit 0 alone (it is the old state that neighbours still need) and put the next state into bit 1. A value of 2 means dead now and alive next, 3 means alive now and alive next, and 1 means alive now but dying. Every neighbour count reads value & 1, which ignores whatever we have already written into bit 1.
Once every cell has been judged, the old generation is no longer needed. Shifting every value right by one drops bit 0 and moves the next state into place.
Approach: In-place two-bit encoding
- For each cell (r, c), count live neighbours among the up to eight in-bounds cells around it, reading only bit 0 with
board[nr][nc] & 1. - If the count is exactly 3, or the count is 2 and the cell itself is live, the cell is alive next generation: set bit 1 with
board[r][c] |= 2. - Do nothing otherwise. Bit 1 stays 0, which encodes dead next generation.
- After the whole scan, walk the board again and replace each value with
value >> 1.
Step-by-step example
board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
- (0,0) is dead with 1 live neighbour, so it stays 0. (0,1) is live with 1 live neighbour and dies of loneliness: it stays 1, meaning live now and dead next.
- (1,0) is dead with exactly 3 live neighbours, (0,1), (2,0) and (2,1), so it becomes 2. (1,2) is live with 3 neighbours and becomes 3.
- (2,0) is live with only 1 live neighbour, (2,1), because (1,1) is dead, so it dies and stays 1. (2,1) has 3 live neighbours and becomes 3. (2,2) has 2 and becomes 3.
- Row 3 sits under the glider: (3,1) is dead with 3 live neighbours, (2,0), (2,1) and (2,2), so it becomes 2. The others stay 0.
- The encoded board is [[0,1,0],[2,0,3],[1,3,3],[0,2,0]]. Shifting every value right by one gives [[0,0,0],[1,0,1],[0,1,1],[0,1,0]].
Code: Python, Java, C++
1class Solution:
2 def gameOfLife(self, board: List[List[int]]) -> None:
3 m, n = len(board), len(board[0])
4 for r in range(m):
5 for c in range(n):
6 live = 0
7 for dr in (-1, 0, 1):
8 for dc in (-1, 0, 1):
9 if (dr or dc) and 0 <= r + dr < m and 0 <= c + dc < n:
10 live += board[r + dr][c + dc] & 1
11 if live == 3 or (live == 2 and board[r][c] & 1):
12 board[r][c] |= 2
13 for r in range(m):
14 for c in range(n):
15 board[r][c] >>= 11class Solution {
2 public void gameOfLife(int[][] board) {
3 int m = board.length, n = board[0].length;
4 for (int r = 0; r < m; r++) {
5 for (int c = 0; c < n; c++) {
6 int live = 0;
7 for (int dr = -1; dr <= 1; dr++) {
8 for (int dc = -1; dc <= 1; dc++) {
9 int nr = r + dr, nc = c + dc;
10 if ((dr != 0 || dc != 0) && nr >= 0 && nr < m && nc >= 0 && nc < n) {
11 live += board[nr][nc] & 1;
12 }
13 }
14 }
15 if (live == 3 || (live == 2 && (board[r][c] & 1) == 1)) {
16 board[r][c] |= 2;
17 }
18 }
19 }
20 for (int r = 0; r < m; r++) {
21 for (int c = 0; c < n; c++) {
22 board[r][c] >>= 1;
23 }
24 }
25 }
26}1class Solution {
2public:
3 void gameOfLife(vector<vector<int>>& board) {
4 int m = board.size(), n = board[0].size();
5 for (int r = 0; r < m; r++) {
6 for (int c = 0; c < n; c++) {
7 int live = 0;
8 for (int dr = -1; dr <= 1; dr++) {
9 for (int dc = -1; dc <= 1; dc++) {
10 int nr = r + dr, nc = c + dc;
11 if ((dr != 0 || dc != 0) && nr >= 0 && nr < m && nc >= 0 && nc < n) {
12 live += board[nr][nc] & 1;
13 }
14 }
15 }
16 if (live == 3 || (live == 2 && (board[r][c] & 1) == 1)) {
17 board[r][c] |= 2;
18 }
19 }
20 }
21 for (int r = 0; r < m; r++) {
22 for (int c = 0; c < n; c++) {
23 board[r][c] >>= 1;
24 }
25 }
26 }
27};Time and space complexity
O(m * n)
Each cell looks at no more than 8 neighbours in the first pass and is shifted once in the second, so the work is a constant times the number of cells.
O(1)
The next generation is stored in the spare bit of each existing integer, so no second board is allocated.
Other approaches
Copy the board (time O(m * n), space O(m * n))
Clone the board, read every neighbour count from the clone and write results into the original. It is the clearest version and a good way to test the in-place one, but it doubles the memory.
Sentinel values (time O(m * n), space O(1))
Mark a live cell that dies as -1 and a dead cell that is born as 2, count a neighbour as live when its absolute value is 1, then map -1 to 0 and 2 to 1. It is the same idea with special values instead of bits.
Common mistakes
- Writing the new value directly into
board[r][c]during the scan. Neighbours judged later read the new generation and get the wrong count. - Counting neighbours with
board[nr][nc] == 1. After marking, a live cell can hold 3, so compareboard[nr][nc] & 1instead. - Counting the cell itself as its own neighbour. Skip the offset (0, 0).
- Forgetting bounds checks at the edges and corners, where a cell has only 3 or 5 neighbours.
Frequently asked questions
Why does Game of Life need both generations at the same time?
The rules apply to all cells at once, so every count must use the old generation. If you write new values as you go, later cells see a mix of old and new neighbours.
How does the two-bit trick keep the old state?
The old state lives in bit 0 and is never changed during the first pass. The new state goes into bit 1. Reading value & 1 always returns the old state, no matter what has been written into bit 1.
How would you handle an infinite board?
Store only the coordinates of live cells in a hash set. For each live cell and its neighbours, count live neighbours from the set and build a new set for the next generation. Work then scales with the number of live cells rather than the board area.
What is the time and space complexity?
O(m * n) time because each cell checks at most eight neighbours, and O(1) extra space because the next state is packed into each cell's spare bit.