LeetCode 289: Game of Life is a Medium matrix problem. This Python walkthrough develops an encoded in-place transition solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Matrix |
| Reusable pattern | encoded in-place transition |
| Complexity | O(mn) time and O(1) extra space |
Recognizing the pattern
Matrix problems become manageable when row, column, layer, or neighbor boundaries are explicit rather than inferred inside nested loops.
For this problem specifically, 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. The invariant worth writing beside the code is: The low bit of every cell remains the original generation until all transitions are computed.
Step-by-step algorithm
- Identify the input state consumed by
gameOfLife(board)and initialize the data required by the encoded in-place transition pattern. - 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.
- After each update, verify the page’s central invariant: The low bit of every cell remains the original generation until all transitions are computed.
- Finish only after the boundary behavior is covered: Bounds exclude off-board neighbors; all cells update simultaneously.
Python solution
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] >>= 1Reading the implementation
The main entry point is gameOfLife(board). The named working state includes rows, live, old; those variables make the encoded in-place transition state visible instead of hiding it in incidental control flow.
The implementation uses 6 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, 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.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. 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. Each update records the current item without invalidating earlier decisions; consequently, the low bit of every cell remains the original generation until all transitions are computed.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(mn) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
An auxiliary matrix can make reads and writes independent, while marker or boundary techniques trade that clarity for lower space use. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
life=[[0,1,0],[0,0,1],[1,1,1],[0,0,0]]; Solution().gameOfLife(life); assert life == [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]Common mistakes and edge cases
- Problem-specific boundary: Bounds exclude off-board neighbors; all cells update simultaneously.
- Pattern-level pitfall: Rectangular inputs, one-row layers, and one-column layers expose off-by-one errors that square examples often hide.
- Invariant check: after every update, confirm that the low bit of every cell remains the original generation until all transitions are computed.
Interview review checklist
- Explain why encoded in-place transition matches the structure of this input.
- State the invariant in one sentence before tracing code: The low bit of every cell remains the original generation until all transitions are computed.
- Derive O(mn) time and O(1) extra space from how many times each element or state is visited.
- Test the boundary explicitly: Bounds exclude off-board neighbors; all cells update simultaneously.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 73. Set Matrix Zeroes · Next: 383. Ransom Note