0

I'm failing cause the output is the same with input even tho it shouldn't be according to my last line(nums=array).

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
    let a=0;
    const array=[];
   
        for(let i=0; i+k<=nums.length-1; i++){
         
           array[i+k]=nums[i];
           
           
        }
        for(let k=Math.ceil(nums.length/2); k<nums.length; k++){
            array[a]=nums[k];
            a++;
        }
     nums=array;
};

Sample test case:

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]

This is a leetcode question called Rotate Array (189). What do I missing? I'm beginner on coding.

Baran
  • 19
  • 3
  • 1
    `nums = array` will not change the argument passed to the call. [JS is always pass-by-value, not pass-by-reference](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language). If you want to change the input, you need to mutate it, not assign to the variable. – VLAZ Apr 26 '22 at 08:21
  • ^^ or *return* the new array, and have the calling code use the return value. – T.J. Crowder Apr 26 '22 at 08:22

0 Answers0