Anjan Dutta

Leet Code 189: Rotate Array

Leet Code 189: Rotate Array

Problem statement:

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

Constraints:

  • 1 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • 0 <= k <= 105

Soultion

/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
const len = nums.length;
k = k % len;
nums = reverse(nums, 0, len-1);
nums = reverse(nums, 0, k-1);
nums = reverse(nums, k, len-1);
};
function reverse(arr = [], l, r) {
while(l<r) {
let temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
return arr;
}