Prison Cells After N Days
Given the prison rules and the constraints, we can note that the state of the cells will eventually repeat after some number of days, leading to a cycle. We can take advantage of this pattern to avoid simulating all ( n ) days, which could be up to ( 10^9 ). Here’s a step-by-step approach:
- Initialize: Create a list
seen
to store previously seen states of the cells. - Simulate Until Repeat: Simulate the prison’s state for each day until a previously seen state is encountered.
- Detect the Cycle: Once a repeated state is found, calculate the cycle length and determine the remaining number of days to simulate by taking ( n \mod \text{{cycle length}} ).
- Simulate the Remainder: Simulate the remaining number of days, starting from the initial state.
Here’s the code:
|
|
This code first simulates the prison’s state until a cycle is detected and then simulates the remaining days. The time complexity is ( O(1) ) since there’s a limited number of possible states (up to 256), and the space complexity is also ( O(1) ).