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:
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: You do not need to return anything.
Input & Output
Example 1 — Standard Pattern
$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]]
💡 Note:The bottom row [1,1,1] creates a classic 'blinker' pattern. Cell at (1,0) gets exactly 3 neighbors so becomes alive. Cell at (1,1) dies from under-population.
Example 2 — All Dead
$Input:board = [[1,1],[1,0]]
›Output:[[1,1],[1,1]]
💡 Note:Top-left has 2 neighbors (survives), top-right has 2 neighbors (survives), bottom-left has 2 neighbors (survives), bottom-right has 3 neighbors (becomes alive).
The key insight is that all cell changes must happen simultaneously. The optimal approach uses in-place state encoding with bit manipulation to avoid extra space. Time: O(m×n), Space: O(1)
Common Approaches
✓
Dfs
⏱️ Time: N/A
Space: N/A
Copy Board Approach
⏱️ Time: O(m×n)
Space: O(m×n)
Make a complete copy of the original board, then for each cell, count its live neighbors and apply the rules to update the original board. This ensures all decisions are based on the original state.
In-Place with State Encoding
⏱️ Time: O(m×n)
Space: O(1)
Instead of using extra space, encode both current and next states in each cell using bit manipulation. Use values 2 and 3 to represent state transitions, allowing us to process everything in one pass.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
int max(int a, int b) {
return a > b ? a : b;
}
struct TreeNode* buildTree(int* arr, int size) {
if (size == 0 || arr[0] == -1) return NULL;
struct TreeNode** queue = (struct TreeNode**)malloc(size * sizeof(struct TreeNode*));
struct TreeNode* root = createNode(arr[0]);
queue[0] = root;
int front = 0, rear = 0;
int i = 1;
while (front <= rear && i < size) {
struct TreeNode* node = queue[front++];
if (i < size && arr[i] != -1) {
node->left = createNode(arr[i]);
queue[++rear] = node->left;
}
i++;
if (i < size && arr[i] != -1) {
node->right = createNode(arr[i]);
queue[++rear] = node->right;
}
i++;
}
free(queue);
return root;
}
int calculateHeightWithoutNode(struct TreeNode* root, int skipNode) {
if (!root || root->val == skipNode) return -1;
int leftH = calculateHeightWithoutNode(root->left, skipNode);
int rightH = calculateHeightWithoutNode(root->right, skipNode);
return 1 + max(leftH, rightH);
}
int* solution(struct TreeNode* root, int* queries, int queriesSize, int* returnSize) {
*returnSize = queriesSize;
int* result = (int*)malloc(queriesSize * sizeof(int));
for (int i = 0; i < queriesSize; i++) {
result[i] = calculateHeightWithoutNode(root, queries[i]);
}
return result;
}
int parseArray(char* str, int** arr) {
int count = 0;
int capacity = 100;
*arr = (int*)malloc(capacity * sizeof(int));
char* token = strtok(str, ",");
while (token != NULL) {
while (isspace(*token)) token++;
if (strncmp(token, "null", 4) == 0) {
(*arr)[count++] = -1;
} else {
(*arr)[count++] = atoi(token);
}
token = strtok(NULL, ",");
}
return count;
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
int main() {
char rootLine[10000];
char queryLine[10000];
fgets(rootLine, sizeof(rootLine), stdin);
fgets(queryLine, sizeof(queryLine), stdin);
rootLine[strlen(rootLine)-1] = '\0';
queryLine[strlen(queryLine)-1] = '\0';
char* rootStr = rootLine + 1;
rootStr[strlen(rootStr)-1] = '\0';
char* queryStr = queryLine + 1;
queryStr[strlen(queryStr)-1] = '\0';
int* rootArr;
int* queries;
int rootSize = parseArray(rootStr, &rootArr);
int queriesSize = parseArray(queryStr, &queries);
struct TreeNode* root = buildTree(rootArr, rootSize);
int returnSize;
int* result = solution(root, queries, queriesSize, &returnSize);
printf("[");
for (int i = 0; i < returnSize; i++) {
printf("%d", result[i]);
if (i < returnSize - 1) printf(",");
}
printf("]\n");
free(rootArr);
free(queries);
free(result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
✓ Linear Space
95.0K Views
MediumFrequency
~15 minAvg. Time
4.2K Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.