Skip to content

Commit

Permalink
Update 0189-rotate-array.js
Browse files Browse the repository at this point in the history
File(s) Modified: 0189-rotate-array.js
Language(s) Used: javascript
Submission URL: https://leetcode.com/problems/rotate-array/submissions/1069667036/
Solution follows the same algorithm shown on the channel (https://www.youtube.com/c/neetcode).
  • Loading branch information
BogdanBTS committed Oct 7, 2023
1 parent 41307ff commit 17f85bb
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions javascript/0189-rotate-array.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,41 @@ var reversePortionOfArray = function(nums,start,end) {
end--;
}
}


/**
* 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) {

k = k % nums.length;

let l = 0;
let r = nums.length - 1;

while (l < r) {
[nums[l], nums[r]] = [nums[r], nums[l]];
l += 1;
r -= 1;
}
l = 0,
r = k - 1;
while (l < r) {
[nums[l], nums[r]] = [nums[r], nums[l]];
l += 1;
r -= 1;
}
l = k;
r = nums.length - 1;
while (l < r) {
[nums[l], nums[r]] = [nums[r], nums[l]];
l += 1;
r -= 1;
}
};

0 comments on commit 17f85bb

Please sign in to comment.