Skip to content

Commit 17f85bb

Browse files
committed
Update 0189-rotate-array.js
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).
1 parent 41307ff commit 17f85bb

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

javascript/0189-rotate-array.js

+38
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,41 @@ var reversePortionOfArray = function(nums,start,end) {
2424
end--;
2525
}
2626
}
27+
28+
29+
/**
30+
* Two Pointers
31+
* https://leetcode.com/problems/rotate-array/
32+
*
33+
* Time O(n) | Space O(1)
34+
* @param {number[]} nums
35+
* @param {number} k
36+
* @return {void} Do not return anything, modify nums in-place instead.
37+
*/
38+
var rotate = function(nums, k) {
39+
40+
k = k % nums.length;
41+
42+
let l = 0;
43+
let r = nums.length - 1;
44+
45+
while (l < r) {
46+
[nums[l], nums[r]] = [nums[r], nums[l]];
47+
l += 1;
48+
r -= 1;
49+
}
50+
l = 0,
51+
r = k - 1;
52+
while (l < r) {
53+
[nums[l], nums[r]] = [nums[r], nums[l]];
54+
l += 1;
55+
r -= 1;
56+
}
57+
l = k;
58+
r = nums.length - 1;
59+
while (l < r) {
60+
[nums[l], nums[r]] = [nums[r], nums[l]];
61+
l += 1;
62+
r -= 1;
63+
}
64+
};

0 commit comments

Comments
 (0)