AlgoInsight

DSA problem

Game of Life

MediumMatrix (2D Array)Pattern: Matrix Manipulationtop300AmazonGoogleMicrosoftDropboxTwo Sigma

According to Wikipedia article, the Game of Life, devised by mathematician John Conway, is a cellular automaton. The board is an m x n grid of cells, where each cell has an initial state: live (represented by 1) or dead (represented by 0). Each cell interacts with its eight neighbors (horizontal, vertical, and diagonal) using four rules.

A live cell with fewer than two live neighbors dies as if caused by under-population. A live cell with two or three live neighbors lives on to the next generation. A live cell with more than three live neighbors dies as if by over-population. A dead cell with exactly three live neighbors becomes a live cell as if by reproduction. The next state of the board is created by applying these rules simultaneously to every cell in the current state, where births and deaths occur at the same instant.

The straightforward solution copies the whole board so that neighbor counts always read the original generation, costing O(m * n) extra space. The challenge asks you to update the board in-place, which means a cell's new value must not corrupt the neighbor count of cells processed later.

The intuition for the optimal in-place approach is to encode both the old and new states in a single integer using bits. The least significant bit holds the current state, and the second bit holds the next state. When counting neighbors you read cell & 1 to recover the original value, while writing the next state into bit 2 with a left shift. After the whole grid is processed, a final pass right-shifts every cell by one to reveal the next generation, all without any auxiliary matrix.

Examples

Example 1
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]]
Explanation: Each cell is updated simultaneously: for instance the center cell at (1,1) has three live neighbors so it becomes live, while several live cells with too few neighbors die.
Example 2
Input: board = [[1,1],[1,0]]
Output: [[1,1],[1,1]]
Explanation: The dead cell at (1,1) has exactly three live neighbors so it is born, and every live cell has two or three live neighbors so all survive.
Example 3
Input: board = [[0,0],[0,0]]
Output: [[0,0],[0,0]]
Explanation: With no live cells, no births can occur and the board stays entirely dead.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

matrixarrayin-placesimulation

Browse all DSA problems