DEV Community

Urfan Guliyev
Urfan Guliyev

Posted on

1 1

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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay