Skip to content

Commit 9d053d0

Browse files
author
Hamid Gasmi
committed
#225 is completed
1 parent 240399e commit 9d053d0

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

09-problems/lc_957_prison_cells.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
class Solution:
2+
"""
3+
calls[i] = 1 if cells[i - 1] == cell[i+1]
4+
cells[i] = 0
5+
Approach:
6+
1. Find the operation that will let me know go from day d to day d+1
7+
2. loop until I get cycle or I get to N (64 possible combinations)
8+
3. loop again N mod cycle
9+
10+
"""
11+
# There're 2**6 states: 65 + 1 (the initial one)
12+
# Time Analysis: O(2**6) = O(1)
13+
# Space Complexity: O(1)
14+
def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
15+
16+
if N == 0:
17+
return cells
18+
19+
# 1. Convert the list to bitmap
20+
cells_state = self._convert_list_bitmap(cells)
21+
22+
# 2. State at Day 1
23+
cells_state = self.next_state(cells_state)
24+
N -= 1
25+
26+
# 3. Find the cycle
27+
cycle = 0
28+
initial_state = cells_state
29+
while N:
30+
31+
N -= 1
32+
cycle += 1
33+
cells_state = self.next_state(cells_state)
34+
if cells_state == initial_state:
35+
break
36+
37+
# 4. If N too small, then stop
38+
if N == 0:
39+
self._convert_int_to_list(cells_state, cells)
40+
return cells
41+
42+
# 5. loop at most cycle - 1 times
43+
for _ in range(N % cycle):
44+
cells_state = self.next_state(cells_state)
45+
46+
# 6. Convert the bitmap to list
47+
self._convert_int_to_list(cells_state, cells)
48+
return cells
49+
50+
def next_state(self, cells_state: int) -> int:
51+
52+
return ( (~(cells_state << 1)) ^ cells_state >> 1) & 0x007e
53+
54+
def _convert_list_bitmap(self, cells: List[int]) -> int:
55+
56+
cells_state = 0
57+
for cell in cells:
58+
cells_state <<= 1
59+
cells_state |= cell
60+
61+
return cells_state
62+
63+
def _convert_int_to_list(self, cells_state, cells: List[int]):
64+
65+
for i in range(7, -1, -1):
66+
cells[i] = cells_state & 1
67+
cells_state >>= 1

0 commit comments

Comments
 (0)