Junior — Middle
How to implement rotating array elements by a specified number of positions?
sobes.tech AI
Answer from AI
There are several approaches to rotate array elements by a specified number of positions. One simple and effective method is to use reversal (flip) of parts of the array.
Example of rotating an array to the right by k positions:
public static void rotate(int[] arr, int k) {
int n = arr.length;
k = k % n; // in case k is greater than array length
reverse(arr, 0, n - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, n - 1);
}
private static void reverse(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
This method first reverses the entire array, then reverses the first k elements, and finally reverses the remaining elements. As a result, the array is shifted to the right by k positions.
If you need to rotate to the left, you can adapt the logic or rotate to the right by n - k positions.