Skip to content

Instantly share code, notes, and snippets.

@AshishKapoor
Last active September 3, 2021 12:41
Show Gist options
  • Save AshishKapoor/54bd429bf0c9c0732870ced4053ca522 to your computer and use it in GitHub Desktop.
Save AshishKapoor/54bd429bf0c9c0732870ced4053ca522 to your computer and use it in GitHub Desktop.
Array rotation solution
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
// using unshift and pop method (Good for first run)
var rotateByUnshift = function(nums, k) {
k = k > nums.length ? k - nums.length : k;
for(var i=0;i<k;i++){
nums.unshift(nums.pop());
}
return nums;
};
// using prototype unshift, slice, and apply (Accepted)
var rotateByApply = function(nums, k) {
k %= nums.length;
if (k !== 0){
var tmp = nums.slice(-k);
nums.splice(-k, k);
Array.prototype.unshift.apply(nums, tmp);
}
return nums;
};
// console.log(rotateByUnshift([7,2,1,3,4,5], 3))
// console.log(rotateByApply([7,2,1,3,4,5], 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment