Game of Life
LeetCode 289 · Medium · solution, intuition & step-by-step walkthrough
In-place state encoding: −1 (dies) and 2 (born).
This is how I solved Game of Life (LeetCode 289), a medium problem from the Matrix pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Every cell must update from the old board, so you can't overwrite values as you go. Encode transitions in place: −1 means 'was alive, now dead', 2 means 'was dead, now alive'. Counting neighbours with abs(value) == 1 still sees the old state.
Approach
- 1
Count live neighbours using abs(cell) == 1.
- 2
A live cell with < 2 or > 3 neighbours becomes −1.
- 3
A dead cell with exactly 3 neighbours becomes 2.
- 4
Final pass: positive → 1, negative → 0.
How I solved it
In-place state encodingPythonO(m·n) time · O(1) space
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
#live_neighbours<2 - dies
#live_neighbours>3 - dies
#live_neighbours==3
m = len(board)
n = len(board[0])
arr_copy=board.copy()
for i in range(m):
for j in range(n):
live_neighbours=0
for di in range(-1,2):
for dj in range(-1,2):
if not (di == 0 and dj == 0):
nrow = i+di
ncol = j+dj
if 0<=nrow<m and 0<=ncol<n and abs(board[nrow][ncol])==1:
live_neighbours+=1
if (live_neighbours<2 or live_neighbours>3) and board[i][j]==1:
board[i][j]=-1
if live_neighbours==3 and board[i][j]==0:
board[i][j]=2
for i in range(m):
for j in range(n):
if board[i][j]>0:
board[i][j]=1
elif board[i][j]<0:
board[i][j]=0
Game of Life — FAQ
What is the intuition behind Game of Life?
Every cell must update from the old board, so you can't overwrite values as you go. Encode transitions in place: −1 means 'was alive, now dead', 2 means 'was dead, now alive'. Counting neighbours with abs(value) == 1 still sees the old state.
How do you solve Game of Life (LeetCode 289)?
1. Count live neighbours using abs(cell) == 1. 2. A live cell with < 2 or > 3 neighbours becomes −1. 3. A dead cell with exactly 3 neighbours becomes 2. 4. Final pass: positive → 1, negative → 0.
What is the time and space complexity of Game of Life?
Time: O(m·n). Space: O(1). (Accepted approach: In-place state encoding.)
What are common mistakes in Game of Life?
board.copy() is shallow — it doesn't protect the rows; the encoding is what makes it correct.