Reputation: 13
I am solving an algorihmic challenge on LeetCode, here it is:
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 1:
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]
Example 2: Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
var rotate = function(nums, k) {
if(k === 0){
return nums;
} else{
const leftPart = nums.slice(0, nums.length - k);
const rightPart = nums.slice(nums.length - k);
const res = rightPart.concat(leftPart);
return res;
}};
What's wrong with my solution, guys?
Upvotes: 1
Views: 202
Reputation: 46
Try this:
var rotate = function(input, k) {
let result = [];
while(k>0){
result.unshift(input.pop())
k--;
}
return(result.concat(input))
};
Example 1:
let nums = [1,2,3,4,5,6,7];
let k = 3;
nums = rotate(nums,k) //[5,6,7,1,2,3,4]
Upvotes: 0
Reputation: 1603
Looks like it works Ok:
var rotate = function(nums, k) {
if(k === 0){
return nums;
} else{
const leftPart = nums.slice(0, nums.length - k);
const rightPart = nums.slice(nums.length - k);
const res = rightPart.concat(leftPart);
return res;
}};
console.log('Output:', rotate([-1,-100,3,99], 2));
Upvotes: 0
Reputation: 2943
let arr = [1,2,3,4,5];
let timesToRotate = 5;
while(timesToRotate > 0) {
arr.unshift(arr.pop());
timesToRotate -= 1;
}
Upvotes: 0
Reputation: 5191
It's wrong because your solution uses more than O(1) extra space.
O(1) extra space means that your solution can't use extra-memory with a size depending on the size of the input. In your solution, you use temporay arrays with a total space equal to the input.
In order to respect the O(1) condition, you have to find a solution using a constant extra memory size. For example, only 1 number.
Upvotes: 1