I am trying to do the circular left shift of an array by n positions using only a single 1D array. I can do it in two arrays, but I haven\'t figured out how to do it using o
Here is the very easy algorithm, with O(1) Space in O(n)
Algorithm
public class ArrayRotator {
private final int[] target;
private final int length;
public ArrayRotator(int[] seed) {
this.target = seed;
this.length = seed.length;
}
public void rotateInline(int numberOfPositions) {
reverse(0, numberOfPositions);
reverse(numberOfPositions + 1, length-1);
reverse(0, length-1);
}
private void reverse(int start, int end) {
for (int i = start; i <= (start + end)/2; i++) {
swap(i, start + end - i);
}
}
private void swap(int first, int second) {
int temp = this.target[second];
this.target[second] = this.target[first];
this.target[first] = temp;
}
}
For example, lets say the array is [1,2,3,4] and n is 2
After step one, you would end up [2,1,3,4]
After Step two, you would end up [2,1,4,3]
After Step three, you would end up [3,4,1,2]