Cyclic Right Rotation
Sangeerththan Balachandran
SSE | Team Lead | Java | React | SpringBoot | Microservices | Plugin Development | CI | CD | MySQL
Problem Description:
Given an array of integers, perform cyclic right rotation by a specified number of positions. A right rotation means that each element in the array is shifted one position to the right, and the last element of the array is moved to the first position. This process is repeated for the given number of rotations.
Input:
Output:
Constraints:
领英推荐
Solution:
import java.util.Arrays;
public class CyclicRotation {
// Solution method that accepts input and returns the rotated array
public static int[] solution(int[] arr, int k) {
int n = arr.length;
if (n == 0 || k == 0) return arr;
k = k % n; // In case k is greater than n
reverse(arr, 0, n - 1); // Reverse the entire array
reverse(arr, 0, k - 1); // Reverse the first 'k' elements
reverse(arr, k, n - 1); // Reverse the remaining elements
return arr; // Return the rotated array
}
// Helper method to reverse a portion of the array from 'start' to 'end'
private static void reverse(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start++] = arr[end];
arr[end--] = temp;
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int k = 2; // Number of rotations
// Call solution method and store the result
int[] rotatedArray = solution(arr, k);
// Output the rotated array
System.out.println("Array after " + k + " right rotations: " + Arrays.toString(rotatedArray));
}
}
Time and Space Complexity:
Time Complexity:
Space Complexity: