DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 189. Rotate Array

Naive Approach

In this i'm just using an extra array to store

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {

    let res = [];
    let n = nums.length;


    /*for case [1,2] sorting 3 times is equivalent to sorting 1 times*/
    k = k % n; //to handle cases where k>n 

    for(let i = n-k ;i<n;i++){
        res.push(nums[i])
    }

    for(let i = 0 ;i<n-k;i++){
        res.push(nums[i])
    }
    for (let i = 0; i < n; i++) {

        nums[i] = res[i];
    }
};
Enter fullscreen mode Exit fullscreen mode

Approach With O(1) space complexity
Image description
Javascript Code

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {

    k = k%nums.length
    const reverseArray = (l,r) =>{

        while(l<r){
            [nums[l] ,nums[r]] = [nums[r] ,nums[l]]
            l++;
            r--;
        }

    }

    // Reverse the entire array
    reverseArray(0, nums.length - 1);
    // Reverse the first k elements
    reverseArray(0, k - 1);
    // Reverse the remaining elements
    reverseArray(k, nums.length - 1);
};
Enter fullscreen mode Exit fullscreen mode

If you still don't understand please go through the video by Neetcode

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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

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

Okay