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 <iostream>
2#include <vector>
3
4void rotate(std::vector<int>& nums, int k) {
5 int n = nums.size();
6 std::vector<int> rotated(n);
7 k = k % n;
8 for (int i = 0; i < n; ++i) {
9 rotated[(i + k) % n] = nums[i];
10 }
11 nums = rotated;
12}
13
14int main() {
15 std::vector<int> nums = {1,2,3,4,5,6,7};
16 int k = 3;
17 rotate(nums, k);
18 for(int num : nums) {
19 std::cout << num << " ";
20 }
21 return 0;
22}
This C++ solution follows similar logic as the C example using a temporary vector to store the rotated results and copying back to the original vector.
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.
1def rotate(nums, k):
2 def reverse(start, end):
3 while start < end:
4 nums[start], nums[end] = nums[end], nums[start]
5 start, end = start + 1, end - 1
6
7 n = len(nums)
8 k %= n
9 reverse(0, n - 1)
10 reverse(0, k - 1)
11 reverse(k, n - 1)
12
13nums = [1,2,3,4,5,6,7]
14k = 3
15rotate(nums, k)
16print(nums)
In Python, the same strategy of reversing segments of the list in-place is applied. This saves space by sidestepping the need for any additional lists.