Firstly, I will make a big assumption that "better" means "I do not want any / several new data structures."
If so, then the simplest solution is the best, since I do not need to bother with time optimization. I know that other solutions are much more elegant, I just posted them because I read the question as "make sure it is minimal in size."
private static String rotate( final char[] a, final int n ) { for(int i = 0; i < n; i++) { char tmp = a[a.length-1]; for(int j = a.length-1; j >= 0; j--) { a[j] = j == 0 ? tmp : a[(j-1+a.length)%a.length]; } } return new String(a); }
So, I quickly cracked it. Basically, I just rotate in length until I rotate n number of times. To optimize it, you could probably take gcd(n, a.length) .
Now, since my solution is pretty terrible, I will also post the following code, taken from here
void reverse_string(char* str, int left, int right) { char* p1 = str + left; char* p2 = str + right; while (p1 < p2) { char temp = *p1; *p1 = *p2; *p2 = temp; p1++; p2--; } } void rotate(char* str, int k) { int n = strlen(str); reverse_string(str, 0, n-1); reverse_string(str, 0, k-1); reverse_string(str, k, n-1); }
This is what I am assuming is a C-style implementation that works faster than mine, using a basic idea that with three changes allows for an inline shift.
As said here
The trick is to perform three feedback operations. One for the entire row, one from index 0 to k-1 and finally index k to n-1. Magically, this will give the correct spinning array without extra space! (Of course you need a temporary swap variable).
I have not tested this property on the blog I am associated with, so I will post it with a salt that seems to work, but I have never tested it myself ...