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…


This content originally appeared on DEV Community and was authored by Rakesh Reddy Peddamallu

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];
    }
};


This content originally appeared on DEV Community and was authored by Rakesh Reddy Peddamallu


Print Share Comment Cite Upload Translate Updates
APA

Rakesh Reddy Peddamallu | Sciencx (2025-01-25T07:42:26+00:00) Leetcode – 189. Rotate Array. Retrieved from https://www.scien.cx/2025/01/25/leetcode-189-rotate-array/

MLA
" » Leetcode – 189. Rotate Array." Rakesh Reddy Peddamallu | Sciencx - Saturday January 25, 2025, https://www.scien.cx/2025/01/25/leetcode-189-rotate-array/
HARVARD
Rakesh Reddy Peddamallu | Sciencx Saturday January 25, 2025 » Leetcode – 189. Rotate Array., viewed ,<https://www.scien.cx/2025/01/25/leetcode-189-rotate-array/>
VANCOUVER
Rakesh Reddy Peddamallu | Sciencx - » Leetcode – 189. Rotate Array. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/01/25/leetcode-189-rotate-array/
CHICAGO
" » Leetcode – 189. Rotate Array." Rakesh Reddy Peddamallu | Sciencx - Accessed . https://www.scien.cx/2025/01/25/leetcode-189-rotate-array/
IEEE
" » Leetcode – 189. Rotate Array." Rakesh Reddy Peddamallu | Sciencx [Online]. Available: https://www.scien.cx/2025/01/25/leetcode-189-rotate-array/. [Accessed: ]
rf:citation
» Leetcode – 189. Rotate Array | Rakesh Reddy Peddamallu | Sciencx | https://www.scien.cx/2025/01/25/leetcode-189-rotate-array/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.