mediumMatrixArrays & Hashing

Game of Life

mediumTime: O(m*n)Space: O(1)

Recognize the pattern

cellular automaton on a gridsimultaneous updatesencode states without losing the present

Brute force idea

A straightforward first read of Game of Life is this: Copy the entire grid, compute next state from the copy. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The deeper shift in Game of Life is this: encode both the current state and the next state inside the same cell, so you can compute the future without erasing the present. The first pass decides what each cell will become, and the second pass makes that future official. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Game of Life is one steady idea: All cells must update simultaneously — a cell's next state depends on its CURRENT neighbors, not already-updated ones. Encoding both states in the cell value avoids needing a copy. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

A common way to get lost in Game of Life is this: Updating cells one by one — that uses the new state of already-processed cells, which corrupts the simultaneous update. The encoding trick preserves the original state. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Arrays & Hashing Pattern