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.
1import java.util.Arrays;
2
3public class RotateArray {
4 public static void rotate(int[] nums, int k) {
5 int n = nums.length;
6 int[] rotated = new int[n];
7 k = k % n;
8 for (int i = 0; i < n; i++) {
9 rotated[(i + k) % n] = nums[i];
10 }
11 System.arraycopy(rotated, 0, nums, 0, n);
12 }
13
14 public static void main(String[] args) {
15 int[] nums = {1,2,3,4,5,6,7};
16 int k = 3;
17 rotate(nums, k);
18 System.out.println(Arrays.toString(nums));
19 }
20}
The Java solution uses simple array rotation logic, similar to C and C++ solutions, with the aid of a temporary array that holds the result before copying back to the original array.
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.
1def rotate(nums, k):
2 def reverse(start, end):
3 while start < end:
4 nums[start], nums[end] = nums[end], nums[start]
5 start, end = start + 1, end - 1
6
7 n = len(nums)
8 k %= n
9 reverse(0, n - 1)
10 reverse(0, k - 1)
11 reverse(k, n - 1)
12
13nums = [1,2,3,4,5,6,7]
14k = 3
15rotate(nums, k)
16print(nums)
In Python, the same strategy of reversing segments of the list in-place is applied. This saves space by sidestepping the need for any additional lists.