Prison Cells After N Days - Problem
Prison Cells After N Days
Imagine a prison with 8 cells in a row, where each cell is either occupied (1) or vacant (0). Every day, the prison undergoes a transformation based on a simple rule:
If a cell has two adjacent neighbors that are both occupied OR both vacant, then the cell becomes occupied the next day. Otherwise, it becomes vacant.
Important: The first and last cells (positions 0 and 7) can't have two adjacent neighbors, so they always become vacant after the first day.
Goal: Given the initial state of prison cells and a number
Example: If cells =
Imagine a prison with 8 cells in a row, where each cell is either occupied (1) or vacant (0). Every day, the prison undergoes a transformation based on a simple rule:
If a cell has two adjacent neighbors that are both occupied OR both vacant, then the cell becomes occupied the next day. Otherwise, it becomes vacant.
Important: The first and last cells (positions 0 and 7) can't have two adjacent neighbors, so they always become vacant after the first day.
Goal: Given the initial state of prison cells and a number
n, determine what the prison looks like after n days of transformation.Example: If cells =
[0,1,0,1,1,0,0,1] and n = 7, you need to simulate 7 days of changes and return the final state. Input & Output
example_1.py โ Basic Simulation
$
Input:
cells = [0,1,0,1,1,0,0,1], n = 7
โบ
Output:
[0,1,1,0,1,1,1,0]
๐ก Note:
After 7 days of applying the transformation rules, the prison reaches this state. Day 7 happens to be the same as Day 1 due to the cyclic nature.
example_2.py โ No Change Case
$
Input:
cells = [1,0,0,1,0,0,1,0], n = 1000000000
โบ
Output:
[0,0,1,1,1,1,1,0]
๐ก Note:
Even with a billion days, we can efficiently compute the result using cycle detection. The pattern repeats every 14 days in this case.
example_3.py โ Edge Case
$
Input:
cells = [1,1,1,1,1,1,1,1], n = 0
โบ
Output:
[1,1,1,1,1,1,1,1]
๐ก Note:
When n=0, no transformations occur, so we return the original state unchanged.
Constraints
- cells.length == 8
- cells[i] is either 0 or 1
- 1 โค n โค 109
- Note: The first and last cells always become 0 after the first day
Visualization
Tap to expand
Understanding the Visualization
1
Initial Configuration
Start with 8 prison cells, each either occupied (1) or vacant (0)
2
Apply Transformation Rules
For each day, cells become occupied if their neighbors match, vacant otherwise
3
Detect Patterns
Track all seen states - when we see a repeat, we've found a cycle
4
Skip to the Answer
Use the cycle to jump directly to day n without simulating every day
Key Takeaway
๐ฏ Key Insight: Since we only have 8 cells with binary values, there are at most 2^8 = 256 possible states. The cellular automaton must enter a cycle, allowing us to skip ahead using modular arithmetic and solve in O(1) time!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code