Question Four - Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n= 7 and k= 3, the array[1,2,3,4,5,6,7]is rotated to[5,6,7,1,2,3,4].

Solution

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 *//**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
    var i;
    var temp;
    for(i = 0; i < k; i++){
      temp = nums.pop();
      nums.unshift(temp);
    }

};

Discussion

This question was a simple one for me. It took a few minutes to figure out however as I was considering moving the elements of the array using their indexes. I then remembered that arrays in JavaScript have a handy unshift method that can be used to place elements at the start of the array. From there the solutionn was easy to implement

var rotate = function(nums, k) {
    var i;
    var temp;
    for(i = 0; i < k; i++){

    }

};

We define the variable i for use in our for loop and we define a temp variable to store the value at the end of the array. We then set up a for loop to run k times. k is the number if times we want to shift the elements of the array.

var rotate = function(nums, k) {
    var i;
    var temp;
    for(i = 0; i < k; i++){
      temp = nums.pop();
      nums.unshift(temp);
    }

};

Inside of the for loop, we pop the last value from the array amd store it in our temp variable. We then add this temp variable to the start of the array using our handy unshift method from above. This process is repeated until we've rotated the values in the array k times.

results matching ""

    No results matching ""