Prison Cells After N Days — LeetCode 957 Python Solution

MediumBit ManipulationArrayHash TableMath
Problem
#957
Reading time
2 min

The problem

There are 8 prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.

Example

Input
cells = [0,1,0,1,1,0,0,1], n = 7
Output
[0,0,1,1,0,0,0,0]
Explanation
The following table summarizes the state of the prison on each day:

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 957. Prison Cells After N Days is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 957. Prison Cells After N Days?
LeetCode 957. Prison Cells After N Days is rated Medium on LeetCode.
What is the time complexity of LeetCode 957. Prison Cells After N Days?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 957. Prison Cells After N Days?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 957. Prison Cells After N Days cover?
LeetCode 957. Prison Cells After N Days is tagged Bit Manipulation, Array, Hash Table and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview