Skip to content

Instantly share code, notes, and snippets.

@radhar
Last active July 16, 2020 14:26
Show Gist options
  • Save radhar/cbaac74a56d761f7bd7c0b9a1773f841 to your computer and use it in GitHub Desktop.
Save radhar/cbaac74a56d761f7bd7c0b9a1773f841 to your computer and use it in GitHub Desktop.
Given an array, rotate the array to the right by k steps, where k is non-negative
Given an array, rotate the array to the right by k steps, where k is non-negative.
Expected: Input: [1,2,7,8,9] & k=3 (3 steps) Output: [7,8,9,1,2]
// implemented function to rotate the array in anticlockwise.
function rotateRight(arrRotate, step){
// adding the new elements to the end of the array based on the step value.
for (var i=0; i<step ; i++)
{
arrRotate.push(arrRotate[i]);
}
// Removing the elements which we recently added to the Array based on the step value.
for (var i=0; i<step; i++)
{
arrRotate.shift();
}
return arrRotate;
}
// passing two parameters such as [1,2,3,4,5,6,7,8,9] and 3 to the rotateRight function
var finalRotateArray = rotateRight([1,2,3,4,5,6,7,8,9], 3);
console.log(finalRotateArray);
Output: [4,5,6,7,8,9,1,2,3]
Example:
var finalRotateArray = rotateRight([1,-2,3,0,4,6,-1,8,9], 3);
console.log(finalRotateArray);
Output: [0,4,6,-1,8,9,1,-2,3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment