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

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up