1

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?

3
  • 1
    What do you mean 'what's wrong?' it seems working to me. are you trying to solve the follow up problem? Commented Aug 3, 2020 at 8:08
  • What makes you think your solution is wrong? Is there a failing test case? Commented Aug 3, 2020 at 8:10
  • Yes, it has passed only 9 tests out of ~25 Commented Aug 3, 2020 at 8:35

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
let arr = [1,2,3,4,5];
let timesToRotate = 5;
while(timesToRotate > 0) {
  arr.unshift(arr.pop());
  timesToRotate -= 1;
}

Comments

0

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));

Comments

0

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.