Prison Cells After N Days (LeetCode 957): Solution and Explanation

Medium
Array
Hash Table
Math
Bit Manipulation

Eight cells change every day: a cell becomes occupied when its two neighbors match and vacant otherwise, and the end cells always empty. Return the cells after n days, where n can be a billion. With cells = [0,1,0,1,1,0,0,1] and n = 7 the answer is [0,0,1,1,0,0,0,0].

Intuition

The whole prison is just 8 bits, so there are at most 256 possible states. Any sequence of states that long must start repeating, which is the only way a billion days can be answered quickly.

After the first day both end cells are always vacant, leaving 6 free bits. Working the rule out shows the states from day 1 onward repeat with a period that divides 14, so day n has the same cells as day (n - 1) % 14 + 1.

Each day can be computed for all cells at once. Store the cells in one integer with cell 0 in the highest bit. Then state << 1 puts every cell's right neighbor in its column and state >> 1 puts its left neighbor there.

XOR of the two shifted copies is 1 exactly where the neighbors differ. NOT flips that to "neighbors are equal", and & 0x7E clears the two end cells and the stray high bits. One line does a full day.

Approach: Bitmask with the 14-day cycle

  1. Pack the cells into state, shifting left and OR-ing in each cell.
  2. Reduce n to (n - 1) % 14 + 1. This keeps day 14 as 14 rather than 0, which matters because day 0 still has its original end cells.
  3. Repeat n times: state = ~((state << 1) ^ (state >> 1)) & 0x7E.
  4. Unpack: cell i is (state >> (7 - i)) & 1.

Step-by-step example

cells = [0,1,0,1,1,0,0,1], n = 7
  1. Pack the cells into state = 01011001.
  2. n = 7 is already within one cycle, so 7 days are simulated.
  3. Day 1: state << 1 = 10110010, state >> 1 = 00101100, XOR = 10011110. NOT and the mask give 01100000.
  4. Days 2 to 7 give 00001110, 01100100, 00000100, 01110100, 00101100 and finally 00110000.
  5. Unpack 00110000 into [0,0,1,1,0,0,0,0].

Code: Python, Java, C++

1class Solution:
2    def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:
3        state = 0
4        for c in cells:
5            state = (state << 1) | c
6        n = (n - 1) % 14 + 1
7        for _ in range(n):
8            state = ~((state << 1) ^ (state >> 1)) & 0x7E
9        return [(state >> (7 - i)) & 1 for i in range(8)]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(1)

At most 14 days are simulated and each day is a constant number of bit operations, no matter how large n is.

Space

O(1)

The whole prison lives in one integer.

Other approaches

Simulate with a seen-state map (time O(2^6 * 8), space O(2^6))

Simulate with arrays and record the day each state first appears. When a state repeats, the difference of days is the cycle length, and the remaining days are reduced modulo it. Does not rely on knowing the period is 14.

Simulate every day (time O(8n), space O(1))

Apply the rule n times on an array. Correct, but a billion days is far too slow.

Common mistakes

  • Using n % 14 directly. When n is a multiple of 14 that gives 0, which returns the original cells, but the original end cells may be occupied while day 14 has them empty.
  • Forgetting the mask. Without & 0x7E the NOT sets every higher bit and both end cells, so the next day reads garbage neighbors.
  • Mixing up the bit order when unpacking. If cell 0 was packed into bit 7, it must be read back from bit 7.
  • Starting the cycle at day 0. The initial state may never come back, because its end cells can be occupied; the cycle starts at day 1.

Frequently asked questions

Why is the period 14?

After day 1 the rule acts on the 6 middle bits as a fixed linear map over XOR (plus a constant). Checking all 64 states shows every orbit has length 1, 7 or 14, so 14 is a common multiple that works for any start.

Do I have to know the number 14?

No. A hash map from state to the day it was seen finds the cycle on the fly, and is the safer answer if you do not remember the period in an interview.

Why does state << 1 hold the right neighbor?

Shifting left moves every bit one position higher. Since cell i sits at bit 7 - i, the bit that lands in cell i's position came from bit 6 - i, which is cell i + 1, the right neighbor.