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.
- Otherwise, it becomes vacant.
Note that because the prison is a row, the first and the last cells in the row can’t have two adjacent neighbors.
You are given an integer array cells
where cells[i] == 1
if the ith
cell is occupied and cells[i] == 0
if the ith
cell is vacant, and you are given an integer n
.
Return the state of the prison after n
days (i.e., n
such changes described above).
Examples
Example 1
|
|
Example 2
|
|
Constraints
cells.length == 8
cells[i]
is either0
or1
.1 <= n <= 10^9
Solution
Method 1 – Cycle Detection and Simulation
Intuition
Since there are only 8 cells, there are at most 2^6 = 64 possible states (since the first and last are always 0 after the first day). We can use a hash map to detect cycles and fast-forward the simulation.
Approach
- Simulate each day, storing the state in a map from tuple to day.
- If a cycle is detected, fast-forward n by the cycle length.
- Continue simulation for the remaining days.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
for practical n, since the state cycles in at most 2^6 = 64 steps. - 🧺 Space complexity:
O(1)
for the state map (bounded by 64 states).