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 by2or3active neighbors remains1. - Isolation or crowding: An active cell (
1) surrounded by fewer than2(0or1) or more than3(4through8) active neighbors becomes0. - Birth: An inactive cell (
0) surrounded by exact count3active neighbors becomes1; for any other neighbor count it stays0.
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 every0 <= r < m1 <= m, n <= 500board[r][c]is0or1O(1)auxiliary space beyond the inputboarditself
Step-by-step walkthrough
Restate the problem
We are given an
m x ngridboardwhere each cell holds0(dead) or1(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)0or10(dead)Underpopulation 1(alive)2or31(alive)Survival 1(alive)4, 5, 6, 7, 80(dead)Overpopulation 0(dead)31(alive)Reproduction 0(dead)anything else 0(dead)Stays dead We must update
boardin-place (modifying the existing row lists without allocating a second grid) andreturn boardat the end.Why overwriting cells in a single pass fails
Suppose we scan row by row and immediately overwrite each cell with its new
0or1value. 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 to1before(1, 0)was processed,(1, 0)counted a brand-new cell as if it had been alive all along.Allocating a full copy of
boardsolves that bug, because you read from the copy and write toboard, but a copy usesO(m * n)extra memory, which the problem forbids. We need every cell to remember its old state while also recording its new state.Key idea: store old and new states in two bits of each cell
Initially, every cell only uses the values
0or1. In binary, integers have many bits, and only the rightmost bit (the ones bit, worth1) is currently being used. The bit right next to it (the twos bit, worth2) is0everywhere!We can pack both generations into a single tiny integer from
0to3:- Ones bit (
CURRENT_BIT = 1, binary01): holds the current state (0or1). We never change this bit during Pass 1. - Twos bit (
NEXT_BIT = 2, binary10): holds the next state (0or1). 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 * currentThat 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)0001(alive)0(dead)0110(dead)1(alive)1021(alive)1(alive)113Three elementary bitwise operations let us read and write each bit cleanly:
- Read current state (
value & 1): bitwise AND with1keeps only the ones bit (0 & 1 = 0,1 & 1 = 1,2 & 1 = 0,3 & 1 = 1). Notice this is identical tovalue % 2. - Mark alive next (
value |= 2): bitwise OR with2sets the twos bit to1without changing the ones bit (0 | 2 = 2,1 | 2 = 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 divisionvalue // 2.
- Ones bit (
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:- Skip
(0, 0): a cell is not its own neighbor. - Check
0 <= neighbor_row < num_rowsand0 <= neighbor_col < num_cols: in Python, negative indices such asboard[-1]are legal and read the last row instead of raising an error. Without explicit0 <= ...bounds, top-row and left-column cells would wrap around to the opposite side of the board. - 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 hold2or3. Masking with& 1extracts 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- Skip
Code the two passes
Now
game_of_liferuns 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 withNEXT_BITequal to0, we only need to setboard[row][col] |= NEXT_BITwhen the cell will be alive next generation (alive now with 2 or 3 neighbors, or dead now with 3 neighbors). - Pass 2 (shift
NEXT_BITdown intoCURRENT_BIT): after every cell has finished reading its neighbors, shift each cell right by 1 bit (board[row][col] >>= 1) so the board holds clean0and1values 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- Pass 1 (encode next state into
Walk through Example 1
Let's trace the
3 x 4Example 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 0Notice that row
0after Pass 1 ([3, 1, 2, 0]) exhibits all four 2-bit combinations at once:- Cell
(0, 0)starts at1(alive) with3live neighbors ((0, 1),(1, 0),(1, 1)): it survives, so1 | 2 = 3(11in binary: alive now, alive next). - Cell
(0, 1)starts at1(alive). Even though(0, 0)already holds3,count_live_neighborsevaluates3 & 1 = 1and counts4original live neighbors ((0, 0),(1, 0),(1, 1),(1, 2)). Cell(0, 1)dies of crowding, soNEXT_BITstays0and the cell remains1(01in binary: alive now, dead next). - Cell
(0, 2)starts at0(dead). Reading(0, 1) & 1 == 1alongside(1, 1)and(1, 2)gives3live neighbors, so(0, 2)is born and becomes0 | 2 = 2(10in binary: dead now, alive next). - Cell
(0, 3)starts at0(dead) with only1live neighbor(1, 2), staying0(00in 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.- Cell
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 (0or1), 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 (adding2when it was0) 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 by2and 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]]:
- Cell
(0, 0)is0with 2 live neighbors ((0, 1)and(1, 0)), so it stays0(binary00). - Cell
(0, 1)is1with 2 live neighbors ((1, 0)and(1, 2)). It survives, so1 | 2 = 3(binary11: alive now, alive next). - Cell
(0, 2)is0, reads3 & 1 = 1from(0, 1)plus1from(1, 2)(2 live neighbors), and stays0. - Cell
(1, 0)is1, reads3 & 1 = 1from(0, 1)(only 1 live neighbor), so it dies and stays1(binary01: alive now, dead next). - Cell
(1, 1)is0, reads1from(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(binary10: dead now, alive next). - Cell
(1, 2)is1; even though(1, 1)already holds2,2 & 1 = 0, so(1, 2)sees only(0, 1)(1 live neighbor) and stays1. - 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)wheremis the number of rows andnis the number of columns. Pass 1 visits each of them * ncells once and checks at most 8 neighbor positions per cell (constant work per cell), and Pass 2 visits each of them * ncells once more to shift its bits. For the maximum500 x 500grid, 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 ofboard, so we allocate only a few integer loop variables and counters regardless of how largemandngrow.
Edge cases
1 x 1grids:[[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 3all1s): 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
0and1values behind (never2or3), so callinggame_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]with0or1in 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] == 1instead ofboard[nr][nc] & 1: once Pass 1 has visited a neighbor, a live cell that survives holds3(so== 1misses it) and a dead cell that is born holds2. Always mask with& 1. - Forgetting
0 <= neighbor_rowand0 <= neighbor_colin Python:board[-1]does not raiseIndexErrorin Python; it silently reads the last row, turning the grid into a wrap-around torus. - Counting
(0, 0)offset: forgettingif row_offset == 0 and col_offset == 0: continueadds a live cell to its own neighbor count. - Returning a new grid without mutating
board: callers checkingboarddirectly 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 hold2or3, you could scan top-to-bottom while keeping copies of only the unmodified previous row and current row (2 * nintegers) instead of the entirem * ngrid. - Transition marker codes (
-1and2): instead of bitmasks, some implementations mark1 -> 0as-1(soabs(val) == 1tests "was alive") and0 -> 1as2, then replace> 0with1and<= 0with0in Pass 2. Two-bit encoding is cleaner because old and new states sit in independent bits (& 1and>> 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
ronly requires reading rowsr - 1,r, andr + 1from 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. Ifnitself is also huge or you want to parallelize across many machines, partition the grid into rectangularB x Btiles; 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 them * ncells and Pass 2 shifts each cell once, doing constant work per cell. Auxiliary space complexity isO(1)because the next generation is stored in the unused twos bit of the existing integers rather than a secondm x nmatrix. In languages with fixed-width arrays (such asuint8_tin C++ orbyte[][]in Java), avoiding the copy savesm * nbytes of heap allocation; in CPython, integers0through3are pre-allocated singleton objects, so replacing0/1references with2/3references 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 cellsL(O(L)) rather than an infinite area. To advance one step, iterate over each(r, c)inlive_cellsand increment a counter dictionaryneighbor_counts[(nr, nc)]for each of its 8 neighbors; only coordinates that appear inneighbor_countscan possibly be alive next (specifically whencount == 3, orcount == 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
- 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?
- 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?
- What data structure would you choose if the coordinate plane were unbounded in every direction and mostly empty?
Similar questions
- Scoring Extracted W-2 Tax Records Against Ground Truth
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One