Based on my Python solution. Here I use a helper class giving me the Kolakoski sequence (that's its name) one element at a time with its `next`

method. It has the first three elements hard-coded, and after that, it uses another instance of the sequence to iterate further. That other instance does the same, so it might eventually use yet another instance. And so on, O(log n) nested Kolakoski objects iterating in parallel at different speeds as needed. Takes O(log n) space and O(n) time.

```
public class Solution {
public int magicalString(int n) {
Kolakoski kolakoski = new Kolakoski();
int ones = 0;
while (n-- > 0)
if (kolakoski.next() == 1)
ones++;
return ones;
}
private class Kolakoski {
private int[] queue = {1, 2, 2};
private int first = 0, last = 2;
private Kolakoski source;
int next() {
if (first > last) {
if (source == null) {
source = new Kolakoski();
source.next();
source.next();
}
int output = queue[last % 3] ^ 3;
for (int k = source.next(); k > 0; k--)
queue[++last % 3] = output;
}
return queue[first++ % 3];
}
}
}
```