LeetCode 289: Game of Life — Python Solution

Solve LeetCode 289: Game of Life in Python with a encoded in-place transition approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyMedium
TopicMatrix
Reusable patternencoded in-place transition
ComplexityO(mn) time and O(1) extra space

What the problem is testing

Store old and new binary states in different bits of each cell, compute every neighbor count from the old bit, then shift to reveal the next state.

Algorithm

  1. Store old and new binary states in different bits of each cell, compute every neighbor count from the old bit, then shift to reveal the next state.
  2. Maintain this invariant: The low bit of every cell remains the original generation until all transitions are computed.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def gameOfLife(self, board):
        rows, cols = len(board), len(board[0])
        for r in range(rows):
            for c in range(cols):
                live = 0
                for dr in (-1, 0, 1):
                    for dc in (-1, 0, 1):
                        if (dr or dc) and 0 <= r + dr < rows and 0 <= c + dc < cols:
                            live += board[r + dr][c + dc] & 1
                old = board[r][c] & 1
                if live == 3 or (old and live == 2): board[r][c] |= 2
        for r in range(rows):
            for c in range(cols): board[r][c] >>= 1

Why this is correct

The proof follows the maintained state: The low bit of every cell remains the original generation until all transitions are computed. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(mn) time and O(1) extra space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

Bounds exclude off-board neighbors; all cells update simultaneously.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 73. Set Matrix Zeroes · Next: 383. Ransom Note