Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Leetcode #189 Rotate Array – What is happening with my logic where it works for one input, but not the other?

Link to the challenge: https://leetcode.com/problems/rotate-array/

I tried to accomplish this using the % operator to get the remainder aka new index. Then while I am iterating through the loop, assign the new value based on the new index.

I know the question also asks to do it in-place, but that’s something I will try after getting this version working.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var rotate = function(nums, k) {
    
    let map = {} // key: old index, value: new index
    const output = [];
    
    for(let i=0; i < nums.length; i++){
        map[i] = (i+k) % nums.length;
        output[i] = nums[map[i]];
    }

    return output;
};

Run 1 (Works):

Input: nums = [-1,-100,3,99], k = 2
Expected: [3,99,-1,-100]
My output: (4) [3, 99, -1, -100]

Run 2 (Incorrect – off by 1 it seems):

Input: nums = [1,2,3,4,5,6,7], k = 3
Expected: [5,6,7,1,2,3,4]
My output: (7) [4, 5, 6, 7, 1, 2, 3]

Any help would be appreciated. Thank you in advanced.

>Solution :

Your map variable is superfluous because you always assign to a given index right before referencing the value at that index:

map[i] = (i+k) % nums.length;
output[i] = nums[map[i]];

may as well be

const newIndex = (i+k) % nums.length;
output[i] = nums[newIndex];

Which should make things clearer what the problem is – you’re assigning to the i index of the new array, not to the newIndex index of the new array. Switch those indicies around and it’ll work.

var rotate = function(nums, k) {
    const output = [];
    for(let i=0; i < nums.length; i++){
        const newIndex = (i+k) % nums.length;
        output[newIndex] = nums[i];
    }

    return output;
};
console.log(rotate([1,2,3,4,5,6,7], 3));

The "Run 1" worked only because, when the array has 4 elements, rotating 2 forwards is the same as rotating 2 backwards.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading