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.
1#include <stdio.h>
2
3void rotate(int* nums, int numsSize, int k) {
4 int rotated[numsSize];
5 k = k % numsSize;
6 for (int i = 0; i < numsSize; ++i) {
7 rotated[(i + k) % numsSize] = nums[i];
8 }
9 for (int i = 0; i < numsSize; ++i) {
10 nums[i] = rotated[i];
11 }
12}
13
14int main() {
15 int nums[] = {1,2,3,4,5,6,7};
16 int k = 3;
17 int numsSize = sizeof(nums)/sizeof(nums[0]);
18 rotate(nums, numsSize, k);
19 for(int i = 0; i < numsSize; i++) {
20 printf("%d ", nums[i]);
21 }
22 return 0;
23}
This C solution creates a temporary array of the same size as the input. It calculates the new index for each element using modulo arithmetic to ensure cyclic behavior, then it fills this temporary array and finally copies it back into 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.
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.