So, below you can find my (very basic and unoptimized) solution to Leetcode's challenge 189 'Rotate Array'. The target of this challenge is posed as follows: Given an array, rotate the array to the right by k steps, where k is non-negative.
Now, my solution is not accepted as somehow the global variable nums remains unchanged after the function call. Why is that? Somehow nums is treated as local variable and doesn't change the passed-in global variable nums. I get that it's probably because of how javascript treats variable scopes but I don't seem to find resources that can help me understand this example.
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
array2 = Array.from(nums)
nums.map((num) => {
array2[(nums.indexOf(num)+k)%nums.length] = num
})
nums = Array.from(array2)
console.log(nums) // returns expected answer
};
Your input
[1,2,3,4,5,6,7]
3
Your stdout
[5,6,7,1,2,3,4]
Your answer
[1,2,3,4,5,6,7]
Expected answer
[5,6,7,1,2,3,4]
numsin-place" is that you should mutate (modify) the array object that is held bynums(ie that is passed in for thenumsparameter), not that you should assign (modify) the localnumsvariable which has no effect outside of the function.