Game of Life
MedPrompt
According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
- Any live cell with fewer than two live neighbors dies as if caused by under-population.
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by over-population.
- Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the m x n grid board. In this process, births and deaths occur simultaneously.
Given the current state of the board, update the board to reflect its next state.
Note that you do not need to return anything.
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]]Example 2:
Input: board = [[1,1],[1,0]]
Output: [[1,1],[1,1]]
Constraints:
m == board.lengthn == board[i].length1 <= m, n <= 25board[i][j]is0or1.
Follow up:
- Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
- In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
Approaches
2 approaches with complexity analysis and trade-offs.
The most straightforward approach is to create a new grid to store the next state while processing the current grid.
Algorithm
- Create a new m x n grid
nextState - For each cell (i,j) in the board:
- Count live neighbors in all 8 directions
- Apply Game of Life rules to determine next state
- Store result in nextState[i][j]
- Copy nextState back to original board
Walkthrough
In this approach, we create a new m x n grid to store the next state of the board. For each cell in the current board, we:
- Count the number of live neighbors using the 8 adjacent cells
- Apply the Game of Life rules to determine the next state
- Store the result in the new grid
- Finally, copy the new grid back to the original board
Here's the implementation:
public void gameOfLife(int[][] board) { int m = board.length; int n = board[0].length; int[][] nextState = new int[m][n]; // Define the 8 directions for neighbors int[] dx = {-1, -1, -1, 0, 0, 1, 1, 1}; int[] dy = {-1, 0, 1, -1, 1, -1, 0, 1}; // Process each cell for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int liveNeighbors = 0; // Count live neighbors for (int k = 0; k < 8; k++) { int newX = i + dx[k]; int newY = j + dy[k]; if (newX >= 0 && newX < m && newY >= 0 && newY < n) { liveNeighbors += board[newX][newY]; } } // Apply rules if (board[i][j] == 1) { if (liveNeighbors < 2 || liveNeighbors > 3) { nextState[i][j] = 0; } else { nextState[i][j] = 1; } } else { if (liveNeighbors == 3) { nextState[i][j] = 1; } } } } // Copy back to original board for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { board[i][j] = nextState[i][j]; } }}Complexity
Time
O(m*n), where m and n are the dimensions of the board
Space
O(m*n) to store the next state grid
Trade-offs
Pros
Simple to understand and implement
No risk of mixing old and new states
Easy to debug
Cons
Uses extra space proportional to the board size
Requires additional copy operation at the end
Not memory efficient for large boards
We can solve this problem in-place by using additional states to encode both the current and next states in the same cell.
Algorithm
- Define new states:
- 2: Live -> Dead
- 3: Dead -> Live
- First pass: For each cell
- Count live neighbors (cells with value 1 or 2)
- Apply rules using new states
- Second pass: Convert all cells back to 0 or 1 using modulo operation
Walkthrough
Instead of using a separate grid, we can use additional states to represent both the current and next states:
- 0: Dead -> Dead
- 1: Live -> Live
- 2: Live -> Dead
- 3: Dead -> Live
This way, we can determine the original state by checking if the number is 1 or 2 (originally live) or 0 or 3 (originally dead).
public void gameOfLife(int[][] board) { int m = board.length; int n = board[0].length; int[] dx = {-1, -1, -1, 0, 0, 1, 1, 1}; int[] dy = {-1, 0, 1, -1, 1, -1, 0, 1}; // First pass: mark the cells with new states for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int liveNeighbors = 0; // Count live neighbors for (int k = 0; k < 8; k++) { int newX = i + dx[k]; int newY = j + dy[k]; if (newX >= 0 && newX < m && newY >= 0 && newY < n) { // Count cells that are originally live (1 or 2) if (board[newX][newY] == 1 || board[newX][newY] == 2) { liveNeighbors++; } } } // Apply rules using new states if (board[i][j] == 1) { if (liveNeighbors < 2 || liveNeighbors > 3) { board[i][j] = 2; // Live -> Dead } } else if (board[i][j] == 0 && liveNeighbors == 3) { board[i][j] = 3; // Dead -> Live } } } // Second pass: restore to final states for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { board[i][j] %= 2; // Convert states back to 0 or 1 } }}Complexity
Time
O(m*n), where m and n are the dimensions of the board
Space
O(1), only uses constant extra space
Trade-offs
Pros
Uses constant extra space
No need for additional grid
Meets the follow-up requirement of in-place solution
Cons
More complex to understand and implement
Harder to debug due to state encoding
Less readable code
Solutions
Solution
public class Solution { public void GameOfLife ( int [][] board ) { int m = board . Length ; int n = board [ 0 ]. Length ; for ( int i = 0 ; i < m ; ++ i ) { for ( int j = 0 ; j < n ; ++ j ) { int live = - board [ i ][ j ]; for ( int x = i - 1 ; x <= i + 1 ; ++ x ) { for ( int y = j - 1 ; y <= j + 1 ; ++ y ) { if ( x >= 0 && x < m && y >= 0 && y < n && board [ x ][ y ] > 0 ) { ++ live ; } } } if ( board [ i ][ j ] == 1 && ( live < 2 || live > 3 )) { board [ i ][ j ] = 2 ; } if ( board [ i ][ j ] == 0 && live == 3 ) { board [ i ][ j ] = - 1 ; } } } for ( int i = 0 ; i < m ; ++ i ) { for ( int j = 0 ; j < n ; ++ j ) { if ( board [ i ][ j ] == 2 ) { board [ i ][ j ] = 0 ; } if ( board [ i ][ j ] == - 1 ) { board [ i ][ j ] = 1 ; } } } } }class Solution { public void gameOfLife ( int [][] board ) { int m = board . length , n = board [ 0 ]. length ; for ( int i = 0 ; i < m ; ++ i ) { for ( int j = 0 ; j < n ; ++ j ) { int live = - board [ i ][ j ]; for ( int x = i - 1 ; x <= i + 1 ; ++ x ) { for ( int y = j - 1 ; y <= j + 1 ; ++ y ) { if ( x >= 0 && x < m && y >= 0 && y < n && board [ x ][ y ] > 0 ) { ++ live ; } } } if ( board [ i ][ j ] == 1 && ( live < 2 || live > 3 )) { board [ i ][ j ] = 2 ; } if ( board [ i ][ j ] == 0 && live == 3 ) { board [ i ][ j ] = - 1 ; } } } for ( int i = 0 ; i < m ; ++ i ) { for ( int j = 0 ; j < n ; ++ j ) { if ( board [ i ][ j ] == 2 ) { board [ i ][ j ] = 0 ; } else if ( board [ i ][ j ] == - 1 ) { board [ i ][ j ] = 1 ; } } } } }class Solution { public: void gameOfLife ( vector < vector < int >>& board ) { int m = board . size (), n = board [ 0 ]. size (); for ( int i = 0 ; i < m ; ++ i ) { for ( int j = 0 ; j < n ; ++ j ) { int live = - board [ i ][ j ]; for ( int x = i - 1 ; x <= i + 1 ; ++ x ) { for ( int y = j - 1 ; y <= j + 1 ; ++ y ) { if ( x >= 0 && x < m && y >= 0 && y < n && board [ x ][ y ] > 0 ) { ++ live ; } } } if ( board [ i ][ j ] == 1 && ( live < 2 || live > 3 )) { board [ i ][ j ] = 2 ; } if ( board [ i ][ j ] == 0 && live == 3 ) { board [ i ][ j ] = - 1 ; } } } for ( int i = 0 ; i < m ; ++ i ) { for ( int j = 0 ; j < n ; ++ j ) { if ( board [ i ][ j ] == 2 ) { board [ i ][ j ] = 0 ; } else if ( board [ i ][ j ] == - 1 ) { board [ i ][ j ] = 1 ; } } } } };class Solution : def gameOfLife ( self , board : List [ List [ int ]]) -> None : m , n = len ( board ), len ( board [ 0 ]) for i in range ( m ): for j in range ( n ): live = - board [ i ][ j ] for x in range ( i - 1 , i + 2 ): for y in range ( j - 1 , j + 2 ): if 0 <= x < m and 0 <= y < n and board [ x ][ y ] > 0 : live += 1 if board [ i ][ j ] and ( live < 2 or live > 3 ): board [ i ][ j ] = 2 if board [ i ][ j ] == 0 and live == 3 : board [ i ][ j ] = - 1 for i in range ( m ): for j in range ( n ): if board [ i ][ j ] == 2 : board [ i ][ j ] = 0 elif board [ i ][ j ] == - 1 : board [ i ][ j ] = 1Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.