Problem Description
Given an 8-cell prison, each cell is either occupied (1) or vacant (0). Each day, the cell states are updated: a cell becomes occupied if its two adjacent neighbors are both occupied or both vacant; otherwise, it becomes vacant. Note that because the first and last cells have only one adjacent neighbor, they will always become vacant on the next day. Given an initial state and a large number N representing days, return the prison state after N days.
Key Insights
- The first and last cells will always become 0 after the first update.
- Because there are a finite number of states (2^6 possible configurations for cells 1 to 6), the states will eventually repeat, forming a cycle.
- Using cycle detection, we can reduce the effective number of days to simulate by taking N modulo the cycle length.
- Simulation of each day is straightforward using state transformation based on neighbor comparison.
Space and Time Complexity
Time Complexity: O(2^6) in worst case (i.e. constant time, as cycle length ≤ 64). Space Complexity: O(2^6) to store seen states (also constant space).
Solution
The idea is to simulate the state transformation day by day until we notice a repetition in states. Once we detect a cycle, we know that further transformations will repeat the earlier states in a loop. We calculate the remaining number of days after accounting for full cycles (by taking modulo with the cycle length). After that, we perform simulation for the remaining days only.
We use a dictionary (or map) to store previously seen states mapped to the remaining days at that moment. When we see a state that has been seen before, we calculate the cycle length. With that, we can speed up the simulation by reducing N (the number of days left) using modulo arithmetic, then simulate only the leftover days.
The transformation for a day uses an auxiliary array where for each cell (except the first and last) the new value is set to 1 if the immediate neighbors have the same value, or 0 otherwise.