In this example, we’ll see how to left rotate an array:
Input:
int rotateBySteps = 2;
int[] arr1 = { 2, 5, 7, 8, 14 };
Output:
[7, 8, 14, 2, 5]
First Rotation: [5, 7, 8, 14, 2]
Second Rotation: [7, 8, 14, 2, 5]
1. Java
public class LeftRotateArray {
static int[] rotLeft(int[] arr, int noOfSteps) {
for (int i = 0; i < noOfSteps; i++) {
int first = arr[0];
for (int j = 0; j <= arr.length - 2; j++) {
arr[j] = arr[j + 1];
}
arr[arr.length - 1] = first;
}
return arr;
}
public static void main(String[] args) throws IOException {
int noOfSteps = 2;
int[] arr = {1, 2, 3, 4, 5};
int[] result = rotLeft(arr, noOfSteps);
System.out.println(Arrays.toString(result));
}
}
Output:
[3, 4, 5, 1, 2]
Complete Java Solutions can be found here: Github Link