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.
1#include <iostream>
2#include <vector>
3
4void reverse(std::vector<int>& nums, int start, int end) {
5 while (start < end) {
6 std::swap(nums[start], nums[end]);
7 start++;
8 end--;
9 }
10}
11
12void rotate(std::vector<int>& nums, int k) {
13 int n = nums.size();
14 k = k % n;
15 reverse(nums, 0, n - 1);
16 reverse(nums, 0, k - 1);
17 reverse(nums, k, n - 1);
18}
19
20int main() {
21 std::vector<int> nums = {1,2,3,4,5,6,7};
22 int k = 3;
23 rotate(nums, k);
24 for(int num : nums) {
25 std::cout << num << " ";
26 }
27 return 0;
28}
The C++ solution leverages in-place reversal operations which transform sections of the array three times to achieve rotation, preserving space.