#957

Prison Cells After N Days

Medium
ArrayHash TableMathBit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the fact that the prison cell states repeat every 14 days. By using this observation, we can reduce the number of iterations significantly, especially for large n.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a loop to simulate the state changes until either n is reduced to 0 or we find a repeating pattern.
  2. 2Step 2: Store the states in a dictionary to detect cycles.
  3. 3Step 3: If a cycle is found, calculate the effective day using n % cycle_length.
solution.py14 lines
1def prisonAfterNDays(cells, n):
2    seen = {}
3    while n > 0:
4        state = tuple(cells)
5        if state in seen:
6            cycle_length = seen[state] - n
7            n %= cycle_length
8        seen[state] = n
9        new_cells = [0] * 8
10        for i in range(1, 7):
11            new_cells[i] = 1 if cells[i-1] == cells[i+1] else 0
12        cells = new_cells
13        n -= 1
14    return cells

Complexity note: The time complexity is O(n) in the worst case, but due to the cycle detection, it can be significantly less for large n. The space complexity is O(n) due to the storage of seen states.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.