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.
1#include <iostream>
2#include <vector>
3
4void reverse(std::vector<int>& nums, int start, int end) {
5 while (start < end) {
6 std::swap(nums[start], nums[end]);
7 start++;
8 end--;
9 }
10}
11
12void rotate(std::vector<int>& nums, int k) {
13 int n = nums.size();
14 k = k % n;
15 reverse(nums, 0, n - 1);
16 reverse(nums, 0, k - 1);
17 reverse(nums, k, n - 1);
18}
19
20int main() {
21 std::vector<int> nums = {1,2,3,4,5,6,7};
22 int k = 3;
23 rotate(nums, k);
24 for(int num : nums) {
25 std::cout << num << " ";
26 }
27 return 0;
28}
The C++ solution leverages in-place reversal operations which transform sections of the array three times to achieve rotation, preserving space.