957. Prison Cells After N Days

There are two key observations to make here

1> The transformations form a cycle.

2>The original array that is passed in, is not a part of that cycle.

Here's a generalizable way to approach this problem w/o having to have a ton of insight:

In the future when you see questions where you have to make a large amount of state transitions over a state space that seems small, just compare the size of the state space to the # of transitions to determine if there's a cycle so you can bound complexity to the size of the state space.

[1,0,0,1,0,0,1,0] => original
[0, 0, 0, 1, 0, 0, 1, 0] => next
[0, 1, 0, 1, 0, 0, 1, 0]
[0, 1, 1, 1, 0, 0, 1, 0]
[0, 0, 1, 0, 0, 0, 1, 0]
[0, 0, 1, 0, 1, 0, 1, 0]
[0, 0, 1, 1, 1, 1, 1, 0]
[0, 0, 0, 1, 1, 1, 0, 0]
[0, 1, 0, 0, 1, 0, 0, 0]
[0, 1, 0, 0, 1, 0, 1, 0]
[0, 1, 0, 0, 1, 1, 1, 0]
[0, 1, 0, 0, 0, 1, 0, 0]
[0, 1, 0, 1, 0, 1, 0, 0]
[0, 1, 1, 1, 1, 1, 0, 0]
[0, 0, 1, 1, 1, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 1, 0] => cycle!

cycle = 14

T: O(n)

S: O(n)

Last updated

Was this helpful?