You calculated k as,
k=r-(n-(j+1));
You could have done,
k=1+(j+r)%n;
If you still face any problem,
Here’s the link to my code.
@harshitbhalla See,
It is obvious that the minimum value of j will be 2 i.e. String would be 111…so on,
so,we have k=r+3-n;
Given that,1 ≤ r ≤n implies 4-n ≤ k ≤ 3
and it’s wrong as you know, 1 ≤ k ≤ n.