cheatsheet1999 / FrontEndCollection

Notes for Fullstack Software Engineers. Covers common data structure and algorithms, web concepts, Javascript / TypeScript, React, and more!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Rotate Array

cheatsheet1999 opened this issue · comments

Given an array, rotate the array to the right by k steps, where k is non-negative.

Screen Shot 2021-09-10 at 8 45 00 PM

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
    k %= nums.length // if k is greater than nums.length then one cycle is completed that means it will remain the same and we have to remainder shifts
    
   let reverse = function(i, j){
    while(i < j){
        [nums[i], nums[j]] = [nums[j], nums[i]];
        i++;
        j--;
    }
   } // suppose  ----->---> 
	reverse(0, nums.length-1); // reverse   <--<------
	 reverse(0, k-1) // reverse first part ---><----
   reverse(k, nums.length-1)// reverse second part --->----->
};

can i work on this?