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

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

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