Last active
July 16, 2020 14:26
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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