Array Rotation Algorithms: Multiple Approaches to Shift Elements Right
Given an array, shift its elements to the right by k positions, where k is a non-negative number.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explenation:
Right rotation by 1 step: [7,1,2,3,4,5,6]
Right rotation by 2 steps: [6,7,1,2,3,4,5]
Right rotasion by 3 steps: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
Right rotation by 1 step: [99,-1,-100,3]
Right rotation by 2 steps: [3,99,-1,-100]
Requirements:
Devise multiple solutions, with at least three different approaches to solve this problem.
Implement an in-place algorithm with O(1) space complexity.
First approach: Create a temporary array with shifted elements, then copy back to original array;
public class ArrayRotator {
public static void performRotation(int[] data, int shiftCount) {
int[] temp = new int[data.length];
for(int index = 0; index < data.length; index++){
temp[(index + shiftCount) % data.length] = data[index];
}
for(int index = 0; index < temp.length; index++){
data[index] = temp[index];
}
}
public static void main(String[] args) {
int[] input = {1,2,3,4};
ArrayRotator.performRotation(input, 2);
for (int index = 0; index < input.length; index++) {
System.out.println(input[index]);
}
}
}
Second approach: Perform k individual shifts; move elements one by one;
public static void performRotation(int[] data, int shiftCount){
int size = data.length;
shiftCount = shiftCount % size;
for (int iteration = 0; iteration < shiftCount; iteration++) {
int lastElement = data[size - 1];
for (int pos = size - 2; pos >= 0; pos--) {
data[pos + 1] = data[pos];
}
data[0] = lastElement;
}
}
Third approach: Reverse the array three times;
public void performRotation(int[] data, int shiftCount) {
if(data.length == 1){
return;
}
shiftCount = shiftCount % data.length;
reverseArray(data, 0, data.length - 1);
reverseArray(data, shiftCount, data.length - 1);
reverseArray(data, 0, shiftCount - 1);
}
public void reverseArray(int[] array, int start, int end){
int iterations = (end - start + 1) / 2;
int swapTemp;
for(int idx = 0; idx < iterations; idx++){
swapTemp = array[start];
array[start] = array[end];
array[end] = swapTemp;
start++;
end--;
}
}