LeetCode 189: Rotate Array
Problem Description
Explanation
To rotate an array to the right by k
steps, we can use the following approach:
- Reverse the entire array.
- Reverse the first
k
elements. - Reverse the remaining elements.
This approach allows us to achieve the rotation in-place with O(1) extra space.
Time complexity: O(n), where n is the number of elements in the array. Space complexity: O(1).
Solutions
class Solution {
public void rotate(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
private void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}
Related LeetCode Problems
Loading editor...