189. Rotate Array (Approach 2 )
Intuition
This approach is based on the fact that when we rotate the array k times, elements from the back end of the array come to the front and the rest of the elements from the front shift backwards.
In this approach, we firstly reverse all the elements of the array. Then, reversing the first k elements followed by reversing the rest elements gives us the required result.
Complexity
Space Complexity
Time Complexity
Code
void reverse(int[] nums, int left, int right) {
while(left < right) {
int temp = nums[left];
nums[left++] = nums[right];
nums[right--] = temp;
}
}
public void rotate(int[] nums, int k) {
k = k % nums.length; // Handle cases where k >= nums.length
if(k == 0) return; // No rotation needed
// Convert right rotation into left rotation of (n - k)
k = nums.length - k;
// Step 1: Reverse the first part (0 to k-1)
reverse(nums, 0, k - 1);
// Step 2: Reverse the second part (k to end)
reverse(nums, k, nums.length - 1);
// Step 3: Reverse the whole array
reverse(nums, 0, nums.length - 1);
}
Last updated