For any given array of length n, rotating it by elements d means moving it's first d elements either at the end of the array or moving the last d elements to the beginning of the array.
For example, for a given array [1, 2, 3, 4, 5, 6, 7], rotating it by 3 elements will result as [4, 5, 6, 7, 1, 2, 3]. Similarly, rotating the same array by 2 elements will result in [3, 4, 5, 6, 7, 1, 2].
An efficient approach to achieve this would be shifting each d elements by one index ahead of its actual index and inserting each element at the end of the array. Below is the program to achieve the same in Java.
public class ArrayRotation { public static int[] rotateBy(int d, int[] input){ int inputLength = input.length; for (int i = 0; i < d; i++){ int temp = input[0]; for(int j = 0; j < inputLength - 1; j++){ input[j] = input[j + 1]; } input[inputLength - 1] = temp; } return input; } public static void main(String[] args){ int[] arr = {1, 2, 3, 4, 5, 6, 7}; int[] output = ArrayRotation.rotateBy(3, arr); System.out.println(Arrays.toString(output)); } }