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.
1function rotate(nums, k) {
2 const n = nums.length;
3 k = k % n;
4 let rotated = nums.slice(-k).concat(nums.slice(0, n - k));
5 for (let i = 0; i < n; i++) {
6 nums[i] = rotated[i];
7 }
8}
9
10let nums = [1,2,3,4,5,6,7];
11let k = 3;
12rotate(nums, k);
13console.log(nums);
This JavaScript solution uses array slicing and concatenation to form the rotated array, then copies it back to the input 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.
1function rotate(nums, k) {
2 function reverse(start, end) {
3 while (start < end) {
4 [nums[start], nums[end]] = [nums[end], nums[start]];
5 start++;
6 end--;
7 }
8 }
9
10 const n = nums.length;
11 k = k % n;
12 reverse(0, n - 1);
13 reverse(0, k - 1);
14 reverse(k, n - 1);
15}
16
17let nums = [1,2,3,4,5,6,7];
18let k = 3;
19rotate(nums, k);
20console.log(nums);
JavaScript can perform this array transition by using internal array reversion. It efficiently uses swap mechanics to operate without supplementary storage.