I’m trying to rotate an array such that given a number and an array, rotate the array by that amount. IE:
abcdefgh
given 3:
fghabcde
What is the best way to do this without using additional data structures/minimal space?
Here is a function header:
public static char[] rotateString(char[] s, int rotateAmount){
}
Firstly, I will make a big assumption that “better” means “I do not want any/as few new data structures”.
If this is the case, then the simplest solution is the best, since I don’t need to bother optimising by time. I know that the other solutions are much more elegant, I’ve only posted it because I’ve read the question as “make sure it’s minimal space-wise”.
So I hacked this out pretty quickly. Basically, I’m just doing rotates by lengths of one until I’ve rotated
nnumber of times. To optimise it you probably could takegcd(n, a.length).Now, since my solution is pretty terrible, I’ll also post the following code taken from here
This is, what I assume to be a C-style implementation that runs faster than mine, using a basic idea that with three reverses, you can implement an inline shift.
As is said here,
I haven’t verified this property on the blog I’ve linked to, so I will post it with a grain of salt that it would appear to work but I’ve never tested it myself…