Bit-Packed In-Place Game of Life Step

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given an m x n integer matrix board where 1 marks an active (live) cell and 0 marks an inactive (dead) cell, advance Conway's cellular automaton by exactly one step in-place using O(1) auxiliary memory.

Every cell looks at up to eight surrounding positions (up, down, left, right, and the four diagonals). Coordinates outside the matrix bounds contain no cells (edges do not wrap around). All cells change state at the same instant based strictly on the starting configuration:

  • Survival: An active cell (1) surrounded by 2 or 3 active neighbors remains 1.
  • Isolation or crowding: An active cell (1) surrounded by fewer than 2 (0 or 1) or more than 3 (4 through 8) active neighbors becomes 0.
  • Birth: An inactive cell (0) surrounded by exact count 3 active neighbors becomes 1; for any other neighbor count it stays 0.

Implement game_of_life(board: List[List[int]]) -> List[List[int]] so that it mutates the existing rows of board directly without allocating a duplicate grid, and returns board. Pack both generations inside each integer cell using two bits — keeping the starting state in bit 0 (value 1) during the neighbor-counting pass while recording the upcoming state in bit 1 (value 2), then shifting every cell right by one bit in a final sweep.

Examples

Example 1

Input:
  board = [
    [1, 1, 0, 0],
    [1, 1, 1, 0],
    [0, 0, 1, 0]
  ]
Output:
  [
    [1, 0, 1, 0],
    [1, 0, 1, 0],
    [0, 0, 1, 0]
  ]

Explanation: Corners (0, 0) and (1, 0) along with (1, 2) and (2, 2) each have 2 or 3 active neighbors and survive; crowded cells (0, 1) (4 neighbors) and (1, 1) (5 neighbors) turn 0; inactive cell (0, 2) touches three active cells ((0, 1), (1, 1), (1, 2)) and turns 1.

Example 2

Input:
  board = [
    [0, 1, 0],
    [1, 0, 1]
  ]
Output:
  [
    [0, 1, 0],
    [0, 1, 0]
  ]

Explanation: (0, 1) touches two active diagonals (1, 0) and (1, 2) so it stays 1; (1, 0) and (1, 2) each touch only (0, 1) (1 neighbor) so both turn 0; (1, 1) touches all three active cells (3 neighbors) so it turns 1.

Example 3

Input:
  board = [
    [0, 1],
    [1, 0]
  ]
Output:
  [
    [0, 0],
    [0, 0]
  ]

Explanation: Each active cell has only 1 active diagonal neighbor and dies from isolation, while each inactive corner has only 2 active neighbors and remains 0.

Constraints

  • m == len(board)
  • n == len(board[r]) for every 0 <= r < m
  • 1 <= m, n <= 500
  • board[r][c] is 0 or 1
  • O(1) auxiliary space beyond the input board itself

Step-by-step walkthrough

  1. Restate the problem

    We are given an m x n grid board where each cell holds 0 (dead) or 1 (alive). Every interior cell has up to 8 neighbors (up, down, left, right, and the 4 diagonals); positions outside the grid boundaries have no cells and contribute 0 live neighbors (the grid does not wrap around).

    (r-1, c-1)  (r-1, c)  (r-1, c+1)
    (r,   c-1)   (r, c)   (r,   c+1)
    (r+1, c-1)  (r+1, c)  (r+1, c+1)
    

    All cells transition simultaneously based only on the starting board:

    Current state Live neighbors Next state Reason
    1 (alive) 0 or 1 0 (dead) Underpopulation
    1 (alive) 2 or 3 1 (alive) Survival
    1 (alive) 4, 5, 6, 7, 8 0 (dead) Overpopulation
    0 (dead) 3 1 (alive) Reproduction
    0 (dead) anything else 0 (dead) Stays dead

    We must update board in-place (modifying the existing row lists without allocating a second grid) and return board at the end.

  2. Why overwriting cells in a single pass fails

    Suppose we scan row by row and immediately overwrite each cell with its new 0 or 1 value. Cells visited later would see a mixture of old and new values instead of the original generation.

    Watch what goes wrong on a horizontal line of three live cells:

    Initial board:         Wrong 1-pass overwrite:       Correct next generation:
      0  0  0                0  1  0  <-- (0,1) becomes 1   0  1  0
      1  1  1                1  1  1  <-- (1,0) now sees    0  1  0
      0  0  0                0  0  0      (0,1)=1 AND       0  1  0
                                          (1,1)=1 (2 live
                                          neighbors), so
                                          (1,0) wrongly
                                          survives!
    

    In the original board, cell (1, 0) had only 1 live neighbor ((1, 1)) and had to die. Because (0, 1) was overwritten to 1 before (1, 0) was processed, (1, 0) counted a brand-new cell as if it had been alive all along.

    Allocating a full copy of board solves that bug, because you read from the copy and write to board, but a copy uses O(m * n) extra memory, which the problem forbids. We need every cell to remember its old state while also recording its new state.

  3. Key idea: store old and new states in two bits of each cell

    Initially, every cell only uses the values 0 or 1. In binary, integers have many bits, and only the rightmost bit (the ones bit, worth 1) is currently being used. The bit right next to it (the twos bit, worth 2) is 0 everywhere!

    We can pack both generations into a single tiny integer from 0 to 3:

    • Ones bit (CURRENT_BIT = 1, binary 01): holds the current state (0 or 1). We never change this bit during Pass 1.
    • Twos bit (NEXT_BIT = 2, binary 10): holds the next state (0 or 1). We turn this bit on during Pass 1 whenever a cell will be alive in the next generation.
      twos bit (next)      ones bit (current)
            |                    |
            v                    v
          [ 0 or 1 ]          [ 0 or 1 ]     --> decimal value = 2 * next + 1 * current
    

    That gives four possible values inside a cell at the end of Pass 1:

    Current state Next state Binary ([next][current]) Decimal stored in board[r][c]
    0 (dead) 0 (dead) 00 0
    1 (alive) 0 (dead) 01 1
    0 (dead) 1 (alive) 10 2
    1 (alive) 1 (alive) 11 3

    Three elementary bitwise operations let us read and write each bit cleanly:

    1. Read current state (value & 1): bitwise AND with 1 keeps only the ones bit (0 & 1 = 0, 1 & 1 = 1, 2 & 1 = 0, 3 & 1 = 1). Notice this is identical to value % 2.
    2. Mark alive next (value |= 2): bitwise OR with 2 sets the twos bit to 1 without changing the ones bit (0 | 2 = 2, 1 | 2 = 3).
    3. Promote next to current (value >> 1): shifting right by 1 bit drops the ones bit and moves the twos bit into the ones place (0 >> 1 = 0, 1 >> 1 = 0, 2 >> 1 = 1, 3 >> 1 = 1). Notice this is identical to integer division value // 2.
  4. Helper: count live neighbors from the ones bit

    To count live neighbors around (row, col), we loop over the 9 offsets (row_offset, col_offset) in {-1, 0, 1} x {-1, 0, 1} and check three things:

    1. Skip (0, 0): a cell is not its own neighbor.
    2. Check 0 <= neighbor_row < num_rows and 0 <= neighbor_col < num_cols: in Python, negative indices such as board[-1] are legal and read the last row instead of raising an error. Without explicit 0 <= ... bounds, top-row and left-column cells would wrap around to the opposite side of the board.
    3. Read board[neighbor_row][neighbor_col] & CURRENT_BIT: neighbors above or to the left of (row, col) have already been visited in Pass 1, so they might currently hold 2 or 3. Masking with & 1 extracts only their original generation state.
    from typing import List
    
    # Each cell board[r][c] stores a 2-bit integer from 0 to 3 (binary 00 to 11):
    #   - CURRENT_BIT (1, binary 01): current generation state (0 = dead, 1 = alive)
    #   - NEXT_BIT    (2, binary 10): next generation state    (0 = dead, 1 = alive)
    CURRENT_BIT = 1
    NEXT_BIT = 2
    
    
    def count_live_neighbors(board: List[List[int]], row: int, col: int) -> int:
        """Count how many of (row, col)'s 8 neighbors are alive in the current generation."""
        num_rows = len(board)
        num_cols = len(board[0])
        live_neighbors = 0
    
        # Visit the 3x3 window centered on (row, col).
        for row_offset in (-1, 0, 1):
            for col_offset in (-1, 0, 1):
                # Skip (0, 0) so we do not count the cell itself as its own neighbor.
                if row_offset == 0 and col_offset == 0:
                    continue
    
                neighbor_row = row + row_offset
                neighbor_col = col + col_offset
    
                # Check bounds explicitly: in Python, board[-1] wraps to the last row
                # instead of raising IndexError, which would corrupt top/left borders.
                if 0 <= neighbor_row < num_rows and 0 <= neighbor_col < num_cols:
                    # Mask with CURRENT_BIT (& 1) because top/left neighbors were already
                    # visited in Pass 1 and may now hold 2 (0 -> 1) or 3 (1 -> 1).
                    live_neighbors += board[neighbor_row][neighbor_col] & CURRENT_BIT
    
        return live_neighbors
    
  5. Code the two passes

    Now game_of_life runs two simple passes over the grid:

    • Pass 1 (encode next state into NEXT_BIT): for each cell, read whether it is currently alive ((board[row][col] & CURRENT_BIT) == 1) and count its live neighbors. Because every cell starts with NEXT_BIT equal to 0, we only need to set board[row][col] |= NEXT_BIT when the cell will be alive next generation (alive now with 2 or 3 neighbors, or dead now with 3 neighbors).
    • Pass 2 (shift NEXT_BIT down into CURRENT_BIT): after every cell has finished reading its neighbors, shift each cell right by 1 bit (board[row][col] >>= 1) so the board holds clean 0 and 1 values again.
    def game_of_life(board: List[List[int]]) -> List[List[int]]:
        if not board or not board[0]:
            return board
    
        num_rows = len(board)
        num_cols = len(board[0])
    
        # Pass 1: compute every cell's next state and store it in NEXT_BIT (value 2)
        # while leaving CURRENT_BIT (value 1) untouched for neighbors checked later.
        for row in range(num_rows):
            for col in range(num_cols):
                is_alive_now = (board[row][col] & CURRENT_BIT) == 1
                live_neighbors = count_live_neighbors(board, row, col)
    
                # Survival rule: a live cell with 2 or 3 live neighbors stays alive.
                if is_alive_now and (live_neighbors == 2 or live_neighbors == 3):
                    board[row][col] |= NEXT_BIT
                # Birth rule: a dead cell with 3 live neighbors becomes alive.
                elif not is_alive_now and live_neighbors == 3:
                    board[row][col] |= NEXT_BIT
                # Otherwise NEXT_BIT stays 0 (the cell dies or remains dead).
    
        # Pass 2: shift every cell right by 1 bit (0->0, 1->0, 2->1, 3->1) so the
        # next state moves into the ones bit and the old state is discarded.
        for row in range(num_rows):
            for col in range(num_cols):
                board[row][col] >>= 1
    
        return board
    
  6. Walk through Example 1

    Let's trace the 3 x 4 Example 1 grid across both passes:

    Initial board             After Pass 1 (2-bit codes)     After Pass 2 (>> 1)
      1  1  0  0                3  1  2  0                     1  0  1  0
      1  1  1  0      -->       3  1  3  0           -->       1  0  1  0
      0  0  1  0                0  0  3  0                     0  0  1  0
    

    Notice that row 0 after Pass 1 ([3, 1, 2, 0]) exhibits all four 2-bit combinations at once:

    • Cell (0, 0) starts at 1 (alive) with 3 live neighbors ((0, 1), (1, 0), (1, 1)): it survives, so 1 | 2 = 3 (11 in binary: alive now, alive next).
    • Cell (0, 1) starts at 1 (alive). Even though (0, 0) already holds 3, count_live_neighbors evaluates 3 & 1 = 1 and counts 4 original live neighbors ((0, 0), (1, 0), (1, 1), (1, 2)). Cell (0, 1) dies of crowding, so NEXT_BIT stays 0 and the cell remains 1 (01 in binary: alive now, dead next).
    • Cell (0, 2) starts at 0 (dead). Reading (0, 1) & 1 == 1 alongside (1, 1) and (1, 2) gives 3 live neighbors, so (0, 2) is born and becomes 0 | 2 = 2 (10 in binary: dead now, alive next).
    • Cell (0, 3) starts at 0 (dead) with only 1 live neighbor (1, 2), staying 0 (00 in binary).

    Finally, Pass 2 shifts every number right by 1 bit (0 -> 0, 1 -> 0, 2 -> 1, 3 -> 1), producing the exact next generation in-place.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Each cell board[r][c] stores a 2-bit integer from 0 to 3 (binary 00 to 11):
    #   - CURRENT_BIT (1, binary 01): current generation state (0 = dead, 1 = alive)
    #   - NEXT_BIT    (2, binary 10): next generation state    (0 = dead, 1 = alive)
    CURRENT_BIT = 1
    NEXT_BIT = 2
    
    
    def count_live_neighbors(board: List[List[int]], row: int, col: int) -> int:
        """Count how many of (row, col)'s 8 neighbors are alive in the current generation."""
        num_rows = len(board)
        num_cols = len(board[0])
        live_neighbors = 0
    
        # Visit the 3x3 window centered on (row, col).
        for row_offset in (-1, 0, 1):
            for col_offset in (-1, 0, 1):
                # Skip (0, 0) so we do not count the cell itself as its own neighbor.
                if row_offset == 0 and col_offset == 0:
                    continue
    
                neighbor_row = row + row_offset
                neighbor_col = col + col_offset
    
                # Check bounds explicitly: in Python, board[-1] wraps to the last row
                # instead of raising IndexError, which would corrupt top/left borders.
                if 0 <= neighbor_row < num_rows and 0 <= neighbor_col < num_cols:
                    # Mask with CURRENT_BIT (& 1) because top/left neighbors were already
                    # visited in Pass 1 and may now hold 2 (0 -> 1) or 3 (1 -> 1).
                    live_neighbors += board[neighbor_row][neighbor_col] & CURRENT_BIT
    
        return live_neighbors
    
    
    def game_of_life(board: List[List[int]]) -> List[List[int]]:
        if not board or not board[0]:
            return board
    
        num_rows = len(board)
        num_cols = len(board[0])
    
        # Pass 1: compute every cell's next state and store it in NEXT_BIT (value 2)
        # while leaving CURRENT_BIT (value 1) untouched for neighbors checked later.
        for row in range(num_rows):
            for col in range(num_cols):
                is_alive_now = (board[row][col] & CURRENT_BIT) == 1
                live_neighbors = count_live_neighbors(board, row, col)
    
                # Survival rule: a live cell with 2 or 3 live neighbors stays alive.
                if is_alive_now and (live_neighbors == 2 or live_neighbors == 3):
                    board[row][col] |= NEXT_BIT
                # Birth rule: a dead cell with 3 live neighbors becomes alive.
                elif not is_alive_now and live_neighbors == 3:
                    board[row][col] |= NEXT_BIT
                # Otherwise NEXT_BIT stays 0 (the cell dies or remains dead).
    
        # Pass 2: shift every cell right by 1 bit (0->0, 1->0, 2->1, 3->1) so the
        # next state moves into the ones bit and the old state is discarded.
        for row in range(num_rows):
            for col in range(num_cols):
                board[row][col] >>= 1
    
        return board
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine a classroom game where every student's next action depends on who is sitting around them right now. If students stand up and leave or sit down one by one, students in the back rows will see the new seating arrangement instead of the starting one. To update simultaneously without setting up a second classroom, each student can hold up two hands: their left hand keeps showing their starting status until everyone has counted, while their right hand records what they will do next. Once everyone has finished counting, everyone drops their left hand and keeps only their right hand.

A naive single-pass loop that writes 0 or 1 straight into board[r][c] fails for the exact same reason: neighbors visited later read already-overwritten values instead of the original generation. Copying the entire m x n grid first fixes correctness, because you read from the frozen copy and write into board, but allocating a second grid uses O(m * n) extra memory, violating the in-place requirement (an in-place algorithm modifies the input data structure directly using only a small, constant amount of extra variables).

Because each integer in board starts as 0 or 1, only its ones bit (binary value 1) is used, leaving its twos bit (binary value 2) free:

  • Bitwise AND (x & 1) masks out every higher bit and reads only the ones bit (0 or 1), letting us read a cell's original state even after its twos bit has been modified.
  • Bitwise OR (x | 2) turns on the twos bit (adding 2 when it was 0) to mark that the cell will be alive in the next generation without disturbing its ones bit.
  • Bitwise right shift (x >> 1) slides every bit one position to the right (dividing by 2 and dropping the remainder), discarding the old state and moving the next state down into the ones bit.

Walk through Example 2 on the 2 x 3 board [[0, 1, 0], [1, 0, 1]]:

  1. Cell (0, 0) is 0 with 2 live neighbors ((0, 1) and (1, 0)), so it stays 0 (binary 00).
  2. Cell (0, 1) is 1 with 2 live neighbors ((1, 0) and (1, 2)). It survives, so 1 | 2 = 3 (binary 11: alive now, alive next).
  3. Cell (0, 2) is 0, reads 3 & 1 = 1 from (0, 1) plus 1 from (1, 2) (2 live neighbors), and stays 0.
  4. Cell (1, 0) is 1, reads 3 & 1 = 1 from (0, 1) (only 1 live neighbor), so it dies and stays 1 (binary 01: alive now, dead next).
  5. Cell (1, 1) is 0, reads 1 from (0, 1) (3 & 1), (1, 0) (1 & 1), and (1, 2) (1 & 1) — 3 live neighbors in total — so it is born: 0 | 2 = 2 (binary 10: dead now, alive next).
  6. Cell (1, 2) is 1; even though (1, 1) already holds 2, 2 & 1 = 0, so (1, 2) sees only (0, 1) (1 live neighbor) and stays 1.
  7. After Pass 1 the board is [[0, 3, 0], [1, 2, 1]]. Pass 2 shifts every cell right by 1 bit (0 -> 0, 1 -> 0, 2 -> 1, 3 -> 1), yielding [[0, 1, 0], [0, 1, 0]].

Complexity

  • Time: O(m * n) where m is the number of rows and n is the number of columns. Pass 1 visits each of the m * n cells once and checks at most 8 neighbor positions per cell (constant work per cell), and Pass 2 visits each of the m * n cells once more to shift its bits. For the maximum 500 x 500 grid, that is roughly 2 million simple operations.
  • Space: O(1) auxiliary space (extra memory beyond the input grid itself). Both generations live inside the existing cells of board, so we allocate only a few integer loop variables and counters regardless of how large m and n grow.

Edge cases

  • 1 x 1 grids: [[1]] has 0 neighbors and dies to [[0]]; [[0]] stays [[0]].
  • Single row (1 x n) or single column (m x 1): end cells have at most 1 neighbor and always die; interior live cells with live neighbors on both sides have 2 neighbors and survive.
  • Grid borders and corners: cells on edges have 5 neighbors and corners have 3; out-of-bounds coordinates count as dead and never wrap to the opposite edge.
  • Dense grids (3 x 3 all 1s): corners have 3 neighbors and survive, edges have 5 and die, and the center has 8 and dies, producing [[1, 0, 1], [0, 0, 0], [1, 0, 1]].
  • Repeated calls on the same board: Pass 2 must leave strictly 0 and 1 values behind (never 2 or 3), so calling game_of_life(board) a second time advances cleanly to generation 2 (for example, an oscillating 3-cell blinker flips vertical and then flips back horizontal).

Common mistakes

  • Overwriting board[r][c] with 0 or 1 in one pass: cells visited later read new-generation values from above and to the left, producing wrong neighbor counts.
  • Checking neighbors with board[nr][nc] == 1 instead of board[nr][nc] & 1: once Pass 1 has visited a neighbor, a live cell that survives holds 3 (so == 1 misses it) and a dead cell that is born holds 2. Always mask with & 1.
  • Forgetting 0 <= neighbor_row and 0 <= neighbor_col in Python: board[-1] does not raise IndexError in Python; it silently reads the last row, turning the grid into a wrap-around torus.
  • Counting (0, 0) offset: forgetting if row_offset == 0 and col_offset == 0: continue adds a live cell to its own neighbor count.
  • Returning a new grid without mutating board: callers checking board directly after the call will still see the old generation.

Alternative approaches

  • Rolling two-row buffer (O(n) extra space): if cells were stored in a strict 1-bit boolean type that could not hold 2 or 3, you could scan top-to-bottom while keeping copies of only the unmodified previous row and current row (2 * n integers) instead of the entire m * n grid.
  • Transition marker codes (-1 and 2): instead of bitmasks, some implementations mark 1 -> 0 as -1 (so abs(val) == 1 tests "was alive") and 0 -> 1 as 2, then replace > 0 with 1 and <= 0 with 0 in Pass 2. Two-bit encoding is cleaner because old and new states sit in independent bits (& 1 and >> 1) with no special cases.

Follow-up questions

  • How would you advance the simulation if the board held billions of cells stored behind a remote row-or-tile API rather than fitting in RAM? Computing row r only requires reading rows r - 1, r, and r + 1 from the current generation, so you can stream the grid from the API one row (or fixed-size chunk) at a time while keeping just a 3-row sliding window in RAM (O(n) memory) and writing finished rows to a separate next-generation table or file. If n itself is also huge or you want to parallelize across many machines, partition the grid into rectangular B x B tiles; each worker fetches its tile plus a 1-cell halo (a 1-cell-wide border copied from neighboring tiles in the current generation) and writes its updated tile to next-generation storage so workers never overwrite cells another worker still needs to read. Tiles containing all zeros and surrounded by a zero halo can be skipped completely.
  • What are the asymptotic time and auxiliary space costs of the two-pass bit-packing method, and how much memory does it save in practice? Time complexity is O(m * n) because Pass 1 checks at most 8 neighbors for each of the m * n cells and Pass 2 shifts each cell once, doing constant work per cell. Auxiliary space complexity is O(1) because the next generation is stored in the unused twos bit of the existing integers rather than a second m x n matrix. In languages with fixed-width arrays (such as uint8_t in C++ or byte[][] in Java), avoiding the copy saves m * n bytes of heap allocation; in CPython, integers 0 through 3 are pre-allocated singleton objects, so replacing 0/1 references with 2/3 references inside the existing row lists allocates zero new list or integer objects.
  • What data structure would you choose if the coordinate plane were unbounded in every direction and mostly empty? Replace the 2D array with a sparse set of coordinates live_cells = {(r, c), ...} storing only currently live cells, so memory and runtime scale with the number of live cells L (O(L)) rather than an infinite area. To advance one step, iterate over each (r, c) in live_cells and increment a counter dictionary neighbor_counts[(nr, nc)] for each of its 8 neighbors; only coordinates that appear in neighbor_counts can possibly be alive next (specifically when count == 3, or count == 2 and coord in live_cells). For gigantic, repetitive patterns over millions of generations, Hashlife stores the sparse world in a quadtree (a tree that recursively splits 2D space into four quadrants) and memoizes (caches) future states of identical sub-squares.

Follow-up questions

Similar questions

More Additive Ai interview questions

All 2 Additive Ai questions →