Prison Cells After N Days

MediumArrays & Hashingsimulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A row of 8 prison cells is described by cells, where cells[i] is 1 if cell i is occupied and 0 if it is vacant. Every day all cells update at the same time: a cell becomes occupied if its two neighbors were both occupied or both vacant the day before; otherwise it becomes vacant. The first and last cells each have only one neighbor, so they are always vacant after the first day. Return the state of the cells after n days. n can be as large as 10^9, so a day-by-day simulation of all n days is too slow.

Examples

Input: cells = [0,1,0,1,1,0,0,1], n = 7
Output: [0,0,1,1,0,0,0,0]
Day 1: [0,1,1,0,0,0,0,0], Day 2: [0,0,0,0,1,1,1,0], ... Day 7: [0,0,1,1,0,0,0,0].
Input: cells = [1,0,0,1,0,0,1,0], n = 1000000000
Output: [0,0,1,1,1,1,1,0]
The states repeat in a cycle, so only n modulo the cycle length matters.

Constraints

  • `cells.length == 8`
  • `cells[i]` is `0` or `1`
  • `1 <= n <= 10^9`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More simulation problems