Prison Cells After N Days — LeetCode 957 Python Solution
- Problem
- #957
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.