Python 0957.py
class Solution:
def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:
# one day
def step(prison):
next = [ 0 ] * 8
# first and last cell will always be empty beginning in step 2
for i in range(1, 7):
next[i] = 1 if prison[i - 1] == prison[i + 1] else 0
return tuple(next)
# compute first transition
# => important because the outer-most cells will be cleared and never be used again
cells = step(cells)
n -= 1
# find first loop
seen = {} # prison => day
current = tuple(cells)
for i in range(n):
current = step(current)
# loop found
if current in seen:
loop = i - seen[current]
n %= loop
break
# keep looking
seen[current] = i
# restart from scratch but with much smaller n
for _ in range(n):
cells = step(cells)
return cells
Difficulty
and has an acceptance rate of about 39% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Bit Manipulation
- Hash Table
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation solves the problem of determining the state of an eight-cell prison after n days. Each day the interior cells (positions 1 through 6) are updated based on the equality of their immediate neighbours, while the outer cells become permanently empty. The algorithm proceeds in three logical phases: a single deterministic transition, detection of a repeating cycle, and a final short-circuited simulation using the reduced number of days.
Step Function Definition
A nested helper named step encapsulates the rule that governs a single day’s transformation. It receives a sequence representing the current prison layout and produces a new layout where the first and last positions are forced to zero and each interior cell is set to one only when its two neighbours share the same value.
def step(prison):
next = [0] * 8
for i in range(1, 7):
next[i] = 1 if prison[i - 1] == prison[i + 1] else 0
return tuple(next)
The function returns a tuple rather than a list, which makes the result immutable and hashable-an essential property for later cycle detection.
Initial Transition
Before entering the main loop the code performs one deterministic transition. This step guarantees that the outer cells are cleared and will never influence subsequent updates, simplifying the state space.
cells = step(cells)
n -= 1
By decrementing n after this first step, the algorithm aligns the remaining number of days with the state that will be processed in the cycle detection phase.
Cycle Detection
The core of the performance optimization lies in recognizing that the prison’s state space is finite (at most 2⁸ different configurations). The algorithm iterates day by day, applying step, while storing each newly encountered state in a dictionary named seen that maps the state to the day index at which it first appeared.
seen = {}
current = tuple(cells)
for i in range(n):
current = step(current)
if current in seen:
loop = i - seen[current]
n %= loop
break
seen[current] = i
When a previously observed configuration reappears, a cycle has been identified. The length of the cycle (loop) is computed as the difference between the current iteration index and the stored index. The remaining number of days n is then reduced modulo the cycle length, effectively discarding whole repetitions of the cycle that would lead to the same final state.
Final Simulation with Reduced Days
After the cycle length has been used to shrink n, the algorithm performs a straightforward simulation for the remaining days. Because n is now bounded by the cycle length, this loop executes at most a few iterations, regardless of the original magnitude of n.
for _ in range(n):
cells = step(cells)
The final prison configuration is returned as a list of integers, matching the expected output format.
Edge Cases Handled
The code implicitly handles several boundary conditions:
- The outer cells are forced to zero after the first transition, ensuring that any input where the outer cells start as one does not affect later steps.
- When the number of days
nis zero, the initial decrement results innbecoming-1. The subsequent loops are bypassed because the range for the cycle detection loop becomes empty, and the final simulation loop also does not execute, leaving the original state unchanged. - If the state repeats immediately (for example, a configuration that is its own successor), the detection logic captures the cycle on the first iteration, reduces
nto zero, and skips further processing. - The use of a tuple for state representation guarantees that dictionary look-ups are reliable and that mutable list objects are not inadvertently altered during cycle detection.
Performance Optimizations
Two primary techniques accelerate the solution:
- Immutable State Representation: Converting the list of cells to a tuple after each step enables constant-time hashing and dictionary storage, which is crucial for fast cycle detection.
- Cycle Modulo Reduction: By identifying the repeating pattern early and applying the modulo operation on the remaining days, the algorithm avoids simulating potentially billions of days. The subsequent loop runs only for the remainder of the cycle, guaranteeing a bounded execution time.
Together, these strategies transform what could be a linear-time simulation proportional to n into an approach whose runtime depends only on the size of the state space (at most 256 distinct configurations) and the length of the detected cycle.
ELI5 - Simplified Explanation
Imagine a long row of eight little houses standing in a line. Some houses have a light on inside, and some are dark. Every day, the houses look at their neighbors to decide what to do for the next day. If a house has the same neighbor on the left and the right, it turns its light on because it likes matching them. If the neighbors are different, the light turns off.
The first and the last house are special because they only have one neighbor, so they always turn their lights off once the first day starts. Because these houses keep changing based on the same rules, the row eventually falls into a repeating pattern. The code first checks what the houses look like after one day. Then, it looks at the sequence of changes to see if the pattern starts to repeat. When the pattern repeats, the code uses a trick with division to skip all the boring, repetitive days and jump straight to the end. After skipping ahead, it finishes any tiny bit of time left to show exactly how the lights look at the very end.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||
|---|---|---|---|---|---|---|
| author | solutions | |||||
| www | AlgoMonster | C++ | Python | Java | ||
| WalkCCC | C++ | Python | Java | |||
| leetcode.ca | C++ | Python | Java | |||
| LeetcodeHelp | C++ | Python | Java | |||
| Progiez | C++ | Python | Java | |||
| github | BigEggStudy | C# | ||||
| black-shadows | C++ | |||||
| charles-wangkai | Java | |||||
| everthis | JS | |||||
| fpdjsns | C++ | |||||
| fsq | C++ | |||||
| JoshCrozier | JS | |||||
| keineahnung2345 | C++ | |||||
| lkwq007 | Python | |||||
| suxrobGM | C# | |||||
| trung-hn | Python | |||||
| varunu28 | Java | |||||
| wisdompeak | C++ | |||||
| AlgoMonster | C++, Python, Java | |||||
| WalkCCC | C++, Python, Java | |||||
| leetcode.ca | C++, Java, Python | |||||
| LeetcodeHelp | C++, Java, Python | |||||
| Progiez | C++, Java, Python | |||||
| BigEggStudy | C# | |||||
| black-shadows | C++, C++ | |||||
| charles-wangkai | Java | |||||
| everthis | JavaScript | |||||
| fpdjsns | C++ | |||||
| fsq | C++ | |||||
| JoshCrozier | JavaScript | |||||
| keineahnung2345 | C++ | |||||
| lkwq007 | Python | |||||
| suxrobGM | C# | |||||
| trung-hn | Python | |||||
| varunu28 | Java | |||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1046: Last Stone Weight
- problem 1051: Height Checker
- problem 779: K-th Symbol in Grammar
- problem 855: Exam Room
- problem 955: Delete Columns to Make Sorted II
- problem 1052: Grumpy Bookstore Owner
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality