I. Left Rotate an Array by One
Problem Statement
Given an array of N integers, left rotate the array by one place. (link)
Optimal Approach
To perform a left rotation of the array by one element involves shifting each element to the left by one position.
Code
public class Solution {
static int[] rotateArray(int[] a, int n) {
int storeFirst = a[0];
for(int i=1; i<n; i++){
a[i-1] = a[i];
}
a[n-1] = storeFirst;
return a;
}
}
II. Rotate Array
Problem Statement
Given an array of integers, rotating array of elements by k elements either left or right. (link)
Optimal Solution
When rotation is encountered, our default strategy is to perform reversal. Whether it involves left or right rotation, the straightforward procedure is:
Identify the partition point.
Reverse each of the two blocks separately.
Reverse the entire array.
Code - I (Using Collections)
public static ArrayList<Integer> rotateArray(ArrayList<Integer> arr, int k) {
int n = arr.size();
k %= n;
Collections.reverse(arr.subList(0, k));
Collections.reverse(arr.subList(k, n));
Collections.reverse(arr.subList(0, n));
return arr;
}
Code - II (Custom Reverse Functionality)
public class Solution {
public static ArrayList<Integer> rotateArray(ArrayList<Integer> arr, int k) {
int n = arr.size();
k %= n;
reverse(arr, 0, k);
reverse(arr, k, n);
reverse(arr, 0, n);
return arr;
}
public static void reverse(List<Integer> arr, int first, int last){
int size = (last+first);
for(int i=first; i<(size>>1); i++){
swap(arr, i, size-i-1);
}
}
public static void swap(List<Integer> arr, int i, int j){
int temp = arr.get(i);
arr.set(i, arr.get(j));
arr.set(j, temp);
}
}