This approach involves using an additional array to store the rotated order of elements. We calculate the new position for each element and place it in the new array. Finally, copy the elements of this new temporary array back into the original array.
Time Complexity: O(n) where n is the number of elements in the array. Space Complexity: O(n) due to the use of an additional array for rotation.
1def rotate(nums, k):
2 n = len(nums)
3 k = k % n
4 rotated = nums[-k:] + nums[:-k]
5 for i in range(n):
6 nums[i] = rotated[i]
7
8nums = [1,2,3,4,5,6,7]
9k = 3
10rotate(nums, k)
11print(nums)
This Python solution uses slicing to create a new rotated list with the elements shifted k positions to the right and then copies the values back to the original list.
This approach involves reversing parts of the array to achieve the rotation without additional space. First, reverse the whole array, then reverse the first k elements, and finally reverse the remaining n-k elements. This series of reversals effectively performs the rotation in-place without needing extra storage.
Time Complexity: O(n). Space Complexity: O(1) as it does not require additional arrays.
1import java.util.Arrays;
2
3class RotateArray {
4 private static void reverse(int[] nums, int start, int end) {
5 while (start < end) {
6 int temp = nums[start];
7 nums[start] = nums[end];
8 nums[end] = temp;
9 start++;
10 end--;
11 }
12 }
13
14 public static void rotate(int[] nums, int k) {
15 int n = nums.length;
16 k = k % n;
17 reverse(nums, 0, n - 1);
18 reverse(nums, 0, k - 1);
19 reverse(nums, k, n - 1);
20 }
21
22 public static void main(String[] args) {
23 int[] nums = {1,2,3,4,5,6,7};
24 int k = 3;
25 rotate(nums, k);
26 System.out.println(Arrays.toString(nums));
27 }
28}
Java also uses the in-place reversal method; by correctly reordering via multiple reversals, the array is rotated without additional memory usage.