Input: nums =[1,2,3,4,5,6,7], k =3Output: [5,6,7,1,2,3,4]Explanation:
rotate 1 steps to the right:[7,1,2,3,4,5,6]rotate 2 steps to the right:[6,7,1,2,3,4,5]rotate 3 steps to the right:[5,6,7,1,2,3,4]
Example 2:
1
2
3
4
5
Input: nums =[-1,-100,3,99], k =2Output: [3,99,-1,-100]Explanation:
rotate 1 steps to the right:[99,-1,-100,3]rotate 2 steps to the right:[3,99,-1,-100]
To rotate an array right by k positions, we need to shift the array to the right by k % n, making space on the left for the last k % n elements of the original array. The simple solution involves using a temporary array of size k % n to store the rightmost k % n elements. Then, shift the original array to the right by k % n positions, and finally copy the saved elements from the temporary array to the left side of the original array. The same logic can be applied for left rotation.
classSolution {
publicvoidrotate(int[] nums, int k) {
k = k % nums.length; // if k > nums.lengthint[] result =newint[nums.length];
for (int i = 0; i<k; i++) {
result[i]= nums[nums.length- k + i];
}
int j = 0;
for (int i = k; i<nums.length; i++) {
result[i]= nums[j];
j++;
}
System.arraycopy(result, 0, nums, 0, nums.length);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution:
defrotate(self, nums: List[int], k: int) ->None:
n = len(nums)
k = k % n # Ensure k is within the bounds of the array size# Create a temporary array to store the result result = [0] * n
# Copy the last k elements to the beginning of the result arrayfor i in range(k):
result[i] = nums[n - k + i]
# Copy the remaining elements to the result arrayfor i in range(k, n):
result[i] = nums[i - k]
# Copy the result array back into the original arrayfor i in range(n):
nums[i] = result[i]
classSolution {
publicvoidrotate(int[] arr, int k) {
if (arr ==null|| k<0) {
thrownew IllegalArgumentException("Illegal argument!");
}
for (int i = 0; i<k; i++) {
for (int j = arr.length- 1; j > 0; j--) {
swap(arr, j, j - 1);
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defrotate(self, arr: list[int], k: int) ->None:
if arr isNoneor k <0:
raiseValueError("Illegal argument!")
n = len(arr)
k = k % n # Ensure k is within the bounds of the array sizefor i in range(k):
for j in range(n -1, 0, -1):
self.swap(arr, j, j -1)
defswap(self, arr: list[int], i: int, j: int) ->None:
arr[i], arr[j] = arr[j], arr[i]
We can perform this in-place using simple reverse swaps:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
A=[1,2,3,4,5,6] and k=2^ rotation point
1. Reverse unrotated part A[..n-k-1]A=[4,3,2,1,5,6]^2. Reverse rotated part A[n-k..]A=[4,3,2,1,6,5]^3. Reverse the whole array
A=[5,6,1,2,3,4]