very simple steps:

poll from the Queue to get the next added number count

put the new number into the Queue
public int magicalString(int n) {
if(n<=0) return 0;
// initialize queue with the third number 2
Queue <Integer> q = new LinkedList<> ();
q.add(2);// start when n > 3 int cnt = 3; int num = 1; int result = 1; while(cnt < n) { int newNumCnt = q.poll(); for (int i = 0; i<newNumCnt && cnt < n ;i++) { q.add(num); cnt ++; result += num == 1 ? 1 : 0; } num = num ^ 3; } return result;
}