Problem : Given of size ‘n’ and a values ‘k’ around which we need to right rotate the array.
Array: [1,2,3,4,5,6,7], K = 3
- Rorate1: 7,1,2,3,4,5,6
- Rotate2: 6,7,1,2,3,4,5
- Rotate3: 5,6,7,1,2,3,4
Solution Using Reversal:
- This solution uses the reverse function to reverse subarrays of the input array.
- First, the whole array is reversed.
- Then, the first k elements are reversed again.
- Finally, the rest of the elements are reversed again.
- This results in the first k elements moving to the end of the array, which is the desired rotation.
public class RightRotateArray {
public void rotate(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
private void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
public static void main(String[] args) {
RightRotateArray rotate = new RightRotateArray();
int[] data = {1,2,3,4,5,6,7};
rotate.rotate(data, 3);
System.out.println(Arrays.toString(data));
}
}