Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #289: Game of Life

In this guide, we solve Leetcode #289 Game of Life in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): Any live cell with fewer than two live neighbors dies as if caused by under-population.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Array, Matrix, Simulation

Intuition

Grid problems are easiest when you define clear row/column boundaries.

A consistent traversal order prevents off-by-one errors.

Approach

Iterate by rows, columns, or layers depending on the requirement.

Keep bounds updated as the traversal progresses.

Steps:

  • Define bounds or directions.
  • Visit cells in order.
  • Update result and move bounds.

Example

Input: board = [[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]]

Python Solution

class Solution: def gameOfLife(self, board: List[List[int]]) -> None: m, n = len(board), len(board[0]) for i in range(m): for j in range(n): live = -board[i][j] for x in range(i - 1, i + 2): for y in range(j - 1, j + 2): if 0 <= x < m and 0 <= y < n and board[x][y] > 0: live += 1 if board[i][j] and (live < 2 or live > 3): board[i][j] = 2 if board[i][j] == 0 and live == 3: board[i][j] = -1 for i in range(m): for j in range(n): if board[i][j] == 2: board[i][j] = 0 elif board[i][j] == -1: board[i][j] = 1

Complexity

The time complexity is O(m×n)O(m \times n)O(m×n), where mmm and nnn are the number of rows and columns of the board, respectively. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy