Skip to content

Commit aacba38

Browse files
committed
Add solution #957
1 parent 484cb99 commit aacba38

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,042 LeetCode solutions in JavaScript
1+
# 1,043 LeetCode solutions in JavaScript
22

33
[https://leetcode.com/](https://leetcode.com/)
44

@@ -766,6 +766,7 @@
766766
954|[Array of Doubled Pairs](./solutions/0954-array-of-doubled-pairs.js)|Medium|
767767
955|[Delete Columns to Make Sorted II](./solutions/0955-delete-columns-to-make-sorted-ii.js)|Medium|
768768
956|[Tallest Billboard](./solutions/0956-tallest-billboard.js)|Hard|
769+
957|[Prison Cells After N Days](./solutions/0957-prison-cells-after-n-days.js)|Medium|
769770
966|[Vowel Spellchecker](./solutions/0966-vowel-spellchecker.js)|Medium|
770771
970|[Powerful Integers](./solutions/0970-powerful-integers.js)|Easy|
771772
976|[Largest Perimeter Triangle](./solutions/0976-largest-perimeter-triangle.js)|Easy|
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* 957. Prison Cells After N Days
3+
* https://leetcode.com/problems/prison-cells-after-n-days/
4+
* Difficulty: Medium
5+
*
6+
* There are 8 prison cells in a row and each cell is either occupied or vacant.
7+
*
8+
* Each day, whether the cell is occupied or vacant changes according to the following rules:
9+
* - If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell
10+
* becomes occupied.
11+
* - Otherwise, it becomes vacant.
12+
*
13+
* Note that because the prison is a row, the first and the last cells in the row can't have two
14+
* adjacent neighbors.
15+
*
16+
* You are given an integer array cells where cells[i] == 1 if the ith cell is occupied and
17+
* cells[i] == 0 if the ith cell is vacant, and you are given an integer n.
18+
*
19+
* Return the state of the prison after n days (i.e., n such changes described above).
20+
*/
21+
22+
/**
23+
* @param {number[]} cells
24+
* @param {number} n
25+
* @return {number[]}
26+
*/
27+
var prisonAfterNDays = function(cells, n) {
28+
const nextState = cells => [
29+
0,
30+
...Array.from({ length: 6 }, (_, i) => cells[i] === cells[i + 2] ? 1 : 0),
31+
0
32+
];
33+
34+
let current = [...cells];
35+
const seen = new Map();
36+
let cycleLength = 0;
37+
38+
while (n > 0) {
39+
const stateKey = current.join('');
40+
if (seen.has(stateKey)) {
41+
const cycleStart = seen.get(stateKey);
42+
cycleLength = cycleStart - n;
43+
n %= cycleLength;
44+
}
45+
seen.set(stateKey, n);
46+
if (n > 0) {
47+
current = nextState(current);
48+
n--;
49+
}
50+
}
51+
52+
return current;
53+
};

0 commit comments

Comments
 (0)