Magicsheet logo

Game of Life

Medium
53.9%
Updated 6/1/2025

Game of Life

What is this problem about?

The Game of Life coding problem asks you to simulate John Conway's cellular automaton. You are given an mimesnm imes n grid containing 0s (dead cells) and 1s (live cells). The grid evolves in discrete steps according to four rules:

  1. A live cell with fewer than two live neighbors dies (under-population).
  2. A live cell with two or three live neighbors lives on.
  3. A live cell with more than three live neighbors dies (over-population).
  4. A dead cell with exactly three live neighbors becomes a live cell (reproduction). The challenge is to update the board in-place to represent the next state.

Why is this asked in interviews?

Companies like Apple, Microsoft, and Google ask the Game of Life interview question to evaluate a candidate's ability to perform Matrix Simulation and manage state transitions without using extra memory. Since updates must happen simultaneously, modifying the board directly will affect subsequent calculations. This tests your cleverness in encoding intermediate states (e.g., using "2" to mean "was alive, now dead") to save O(mimesn)O(m imes n) space.

Algorithmic pattern used

This problem uses an In-Place State Encoding pattern.

  1. Instead of using just 0 and 1, introduce new states to remember the past and dictate the future:
    • 0: Was dead, remains dead.
    • 1: Was alive, remains alive.
    • 2: Was alive, now dead (treat as 1 when counting neighbors).
    • 3: Was dead, now alive (treat as 0 when counting neighbors).
  2. Iterate through the board, count the original live neighbors (values 1 and 2), and apply the rules to update cells to 2 or 3.
  3. Do a second pass to finalize the states (convert 2 to 0, and 3 to 1).

Example explanation

Suppose a cell is 1 and has 4 live neighbors (values are 1).

  • Rule 3 applies (over-population).
  • Instead of changing it to 0 immediately, change it to 2.
  • When its right neighbor calculates its own live neighbors, it sees the 2 and knows "this cell was alive," counting it correctly.
  • In the second pass, the 2 becomes 0.

Common mistakes candidates make

  • Sequential Updates: Modifying cells immediately to 0 or 1, which breaks the rules for neighboring cells that haven't been processed yet.
  • Using an extra board: Creating a copy of the matrix to store the next state. While correct and O(mimesn)O(m imes n) time, it fails the "in-place" (O(1)O(1) space) requirement often explicitly requested by interviewers.
  • Boundary checks: Failing to correctly handle the edges and corners of the board when checking the 8 neighbors.

Interview preparation tip

State encoding is a powerful trick for any grid-based cellular automaton problem. If you need to know both the old and new value simultaneously, map the transition to a new integer or use bit manipulation (e.g., store the next state in the 2nd bit of the integer).

Similar Questions