LeetCode Solutions

957. Prison Cells After N Days

Time:

Space:

			

class Solution {
 public:
  vector<int> prisonAfterNDays(vector<int>& cells, int N) {
    vector<int> firstDayCells;
    vector<int> nextDayCells(cells.size());

    for (int day = 0; N-- > 0; cells = nextDayCells, ++day) {
      for (int i = 1; i + 1 < cells.size(); ++i)
        nextDayCells[i] = cells[i - 1] == cells[i + 1];
      if (day == 0)
        firstDayCells = nextDayCells;
      else if (nextDayCells == firstDayCells)
        N %= day;
    }

    return cells;
  }
};
			

class Solution {
  public int[] prisonAfterNDays(int[] cells, int N) {
    int[] firstDayCells = new int[cells.length];
    int[] nextDayCells = new int[cells.length];

    for (int day = 0; N-- > 0; cells = nextDayCells.clone(), ++day) {
      for (int i = 1; i + 1 < cells.length; ++i)
        nextDayCells[i] = cells[i - 1] == cells[i + 1] ? 1 : 0;
      if (day == 0)
        firstDayCells = nextDayCells.clone();
      else if (Arrays.equals(nextDayCells, firstDayCells))
        N %= day;
    }

    return cells;
  }
}
			

class Solution:
  def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
    nextDayCells = [0] * len(cells)
    day = 0

    while N > 0:
      N -= 1
      for i in range(1, len(cells) - 1):
        nextDayCells[i] = 1 if cells[i - 1] == cells[i + 1] else 0
      if day == 0:
        firstDayCells = nextDayCells.copy()
      elif nextDayCells == firstDayCells:
        N %= day
      cells = nextDayCells.copy()
      day += 1

    return cells