Home > other >  Leetcode #189 Rotate Array - What is happening with my logic where it works for one input, but not t
Leetcode #189 Rotate Array - What is happening with my logic where it works for one input, but not t

Time:09-10

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.

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.

CodePudding user response:

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.

  • Related