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.
1using System;
2
3public class 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 Console.WriteLine(string.Join(",", nums));
27 }
28}
This C# solution applies three-layer inversion directly on the input array; the list is altered systematically using swaps without further resources.