Game of Life

Free with account Updated Nov 19, 2026 · 6 min read
On this page

    Problem statement

    A grid of cells, each alive (1) or dead (0), moves forward one generation. Every cell looks at its eight neighbours (horizontal, vertical, diagonal). A live cell with 2 or 3 live neighbours stays alive; any other live cell dies. A dead cell with exactly 3 live neighbours comes alive. All cells change at the same moment. Update the grid in place.

    Conway's Game of Life is a classic grid-simulation question. The rules are easy; the interview is about the simultaneous update: you must compute the next state from the old one while overwriting the same grid. Original problem: LeetCode 289.

    Example

    Two dead cells with exactly three live neighbours are born; the four live cells each have two or three neighbours and survive.
    Two dead cells with exactly three live neighbours are born; the four live cells each have two or three neighbours and survive.
    Input:              Output:
    0 1 0 0             0 1 1 0
    0 1 1 0             0 1 1 0
    0 0 1 0             0 1 1 0
    0 0 0 0             0 0 0 0
    Input:  [[0,0,0],[1,1,1],[0,0,0]]      # a "blinker"
    Output: [[0,1,0],[0,1,0],[0,1,0]]      # flips between horizontal and vertical

    Constraints (assumed)

    • 1 ≤ rows, cols ≤ 25; each cell is 0 or 1.
    • Cells outside the grid count as dead.

    What this question tests

    • Seeing that an in-place update breaks the simultaneous rule, and fixing it.
    • Encoding two states in one cell (bit tricks or extra marker values) to get O(1) extra space.
    • Clean neighbour loops with boundary checks.

    Questions to ask first

    1. Must it be in place, or can I use a copy? (Here: in place; a copy is the first step.)
    2. What happens at the edges? (Here: outside counts as dead. The alternative is a wrap-around board.)
    3. Is the board finite? (Here: yes. An infinite board is a common follow-up.)
    4. How many generations? (Here: one. Many generations change what's worth optimising.)