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.
1using System;
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 for (int i = 0; i < n; i++) {
12 nums[i] = rotated[i];
13 }
14 }
15
16 public static void Main(string[] args) {
17 int[] nums = {1,2,3,4,5,6,7};
18 int k = 3;
19 Rotate(nums, k);
20 Console.WriteLine(string.Join(",", nums));
21 }
22}
This C# implementation is analogous to previous logic where a helper array is used to store the rotated result and copied 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.
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.