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.
1def rotate(nums, k):
2 n = len(nums)
3 k = k % n
4 rotated = nums[-k:] + nums[:-k]
5 for i in range(n):
6 nums[i] = rotated[i]
7
8nums = [1,2,3,4,5,6,7]
9k = 3
10rotate(nums, k)
11print(nums)
This Python solution uses slicing to create a new rotated list with the elements shifted k positions to the right and then copies the values back to the original list.
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.