Input: arr[] = [1, 2, 3, 4, 5, 6], k =2.
Output: [5, 6, 1, 2, 3, 4]
Explanation: After 1st rotation → [6, 1, 2, 3, 4, 5], After 2nd rotation → [5, 6, 1, 2, 3, 4]
Input: arr[] = [1, 2, 3, 4, 5], k = 4.
Output: [2, 3, 4, 5, 1]
The main idea of this approach is to rotate the array to the right by one position, k
times, using recursion. In each recursive call, the last element of the array is stored temporarily, all other elements are shifted one position to the right, and the saved element is placed at the front. This operation effectively performs a single right rotation. The function then calls itself with k - 1 until
k r
eaches zero, at which point the recursion stops.
The main idea is to first ensures that k is within bounds by taking k %
n, where n
is the array size. Then, we create a temporary result array where the last k
elements of the original array are placed at the beginning. The remaining n -
k elements are then copied after these. Finally, we copy all elements from the result array back to the original array to achieve an in-place update. This method uses index arithmetic to calculate positions efficiently.
Take the example arr[] = [1, 2, 3, 4, 5, 6] with k = 2.
After rotating the array to the right by 2 positions, we get:
[5, 6, 1, 2, 3, 4]
This shows that the last k elements (5, 6) move to the front in the same order, while the first n - k elements (1, 2, 3, 4) shift to the right.
How to Achieve This Efficiently:
Instead of shifting elements one by one, we can use the reversal algorithm, which works in three simple steps:
- Reverse the last k elements.
- Reverse the first n - k elements.
- Reverse the entire array.