Rotate Array
Question
Given an array, rotate the array to the right by k steps, where k is non-negative.
Follow up: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Could you do it in-place with O(1) extra space?
Example:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Analyzation
Brute Force
Rotate the array k times, rotate 1 element each time.
The Code
public class Solution {
public void rotate(int[] nums, int k) {
int temp, previous;
for (int i = 0; i < k; i++) {
previous = nums[nums.length - 1];
for (int j = 0; j < nums.length; j++) {
temp = nums[j];
nums[j] = previous;
previous = temp;
}
}
}
}
Time & Space Complexity
- Time Complexity: Each element has been rotated 1 step by k times so it is
O(n * k)
. - Space Complexity: Since we only use constant number of variables, the Space Complexity is
O(1)
.
Optimization
Rotate 3 times
We know that k % n tail elements will be moved to the head. Therefore, rotate the whole array, then rotate the first k elements, finally rotate the last n - k elements.
class Solution {
public void rotate(int[] nums, int k) {
k %= nums.length;
helper(nums, 0, nums.length - 1);
helper(nums, 0, k - 1);
helper(nums, k, nums.length - 1);
}
public void helper(int[] nums, int start, int end){
while(start < end){
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}
Time & Space Complexity
- Time Complexity: Since we rotate n elements by 3 times so it is O(3n) which is
O(n)
. - Space Complexity: Since we only use constant number of variables, the Space Complexity is
O(1)
.