Back to DSA
Rotate Array
mediumShift every element of an integer array to the right by k positions. Elements that move past the end wrap around to the beginning. The value of k is non-negative and may exceed the array's length.
Examples
Example 1:
Input:
arr = [10,20,30,40,50], k = 2Output:
[40,50,10,20,30]Explanation: After two right rotations, the last two elements wrap to the front.
Example 2:
Input:
arr = [5,-3,8], k = 4Output:
[8,5,-3]Explanation: Since k=4 exceeds the length 3, the effective rotation is 4 mod 3 = 1 step. The last element wraps to the front.
Hints
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--;
}
}
}Time complexity
O(n)Space complexity
O(1)