An array of elements is given arr
arr is of length n
Right rotate array by k elements
Time complexity O(n) and space complexity O(1)
Sample Input:
arr = {1,2 ,3,4,5}
n = 5
k = 2
Output :
arr = {4,5,1,2,3}
💡Strategies for Solving This Problem
The Rotation Trick
Got this at Microsoft. It seems simple but most people do it the hard way with extra space. The elegant solution uses reversals - it's one of those "once you see it, you can't unsee it" tricks.
Naive Approach
Create a new array, copy elements to rotated positions. Works but uses O(n) extra space. Interviewer will ask "Can you do it in-place?"
The Reversal Trick
To rotate right by k positions:
- Reverse entire array
- Reverse first k elements
- Reverse remaining n-k elements
Example: [1,2,3,4,5] rotate right by 2
- Reverse all: [5,4,3,2,1]
- Reverse first 2: [4,5,3,2,1]
- Reverse last 3: [4,5,1,2,3] ✓
O(n) time, O(1) space. This is what they want.
Why It Works
Think about it: rotation moves the last k elements to the front. By reversing, we're essentially moving them but in reverse order. Then we fix each part's order.
My Microsoft interviewer said "This is a classic trick. If you didn't know it before, you do now."
Edge Cases
- k > n: Use k % n (rotating n times = original array)
- k = 0 or k = n: No rotation needed
- Empty array: Return as-is