Leetcode - Rotate Array (with JavaScript)

urfan

Urfan Guliyev

Posted on July 4, 2020

Leetcode - Rotate Array (with JavaScript)

Today I am going to show how to solve the Leetcode Rotate Array algorithm problem.

Here is the problem:
Alt Text

There are several ways to solve this problem. The most basic solution is to remove the last element from the array and place it in front of the array K number of times.

var rotate = function(nums, k) {
    for (let i = 0; i < k; i++) {
        nums.unshift(nums.pop()) 
    }
    return nums;
};
Enter fullscreen mode Exit fullscreen mode

But I decided to use a different approach. In this solution, I first reverse all elements of the array. Afterwards, I reverse again the first k elements and then reverse the rest of elements.

Original List : 1 2 3 4 5 6 7
After reversing all numbers : 7 6 5 4 3 2 1
After reversing first k numbers : 5 6 7 4 3 2 1
After revering last n-k numbers (Result) : 5 6 7 1 2 3 4

1) First I create my own reverse function.

var rotate = function(nums, k) {

    var reverse = function(nums, start, end) {
        while (start < end) {
            var temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start ++;
            end --;
        }
    }
};
Enter fullscreen mode Exit fullscreen mode

2) Then I can start reversing elements of the array.

var rotate = function(nums, k) {

    var reverse = function(nums, start, end) {
        while (start < end) {
            var temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start ++;
            end --;
        }
    }

    k = k % nums.length
    reverse(nums, 0, nums.length - 1)
    reverse(nums, 0, k-1)
    reverse(nums, k, nums.length - 1)
};
Enter fullscreen mode Exit fullscreen mode

You might be wondering why we need to do k = k % nums.length

Imagine we have an array [1,2,3,4,5]. What happens when you rotate it by 5 steps? All of the elements stay in place. Essentially, no change occurred because the size of the array is also 5.
So rotating it by 5 (the size of the array) gives you the same result as rotating it by 0. Similarly, rotating it by 6 gives you the same result as rotating it by 1. Rotating it by 7 gives you the same result as rotating it by 2.

💖 💪 🙅 🚩
urfan
Urfan Guliyev

Posted on July 4, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related