Skip to content

Commit

Permalink
Create 0189-rotate-array.js
Browse files Browse the repository at this point in the history
Solved rotate-array in JS.
  • Loading branch information
aadil42 authored Jun 20, 2023
1 parent 6e1801d commit f3898a5
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions javascript/0189-rotate-array.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Two Pointers
* https://leetcode.com/problems/rotate-array/
*
* Time O(n) | Space O(1)
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {

// if the k exceeds the length of nums.
k = k % nums.length;

nums.reverse();
reversePortionOfArray(nums, 0, k - 1);
reversePortionOfArray(nums,k, nums.length - 1);
};

var reversePortionOfArray = function(nums,start,end) {
while(start < end) {
[nums[start],nums[end]] = [nums[end],nums[start]];
start++;
end--;
}
}

0 comments on commit f3898a5

Please sign in to comment.