-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0189-rotate-array.js
More file actions
34 lines (29 loc) · 847 Bytes
/
0189-rotate-array.js
File metadata and controls
34 lines (29 loc) · 847 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Rotate Array
* Time Complexity: O(N)
* Space Complexity: O(1)
*/
var rotate = function (nums, k) {
const arraySize = nums.length;
if (arraySize === 0 || arraySize === 1) {
return;
}
const rotationsCount = k % arraySize;
if (rotationsCount === 0) {
return;
}
const swapElements = (startIdx, endIdx) => {
let leftBoundary = startIdx;
let rightBoundary = endIdx;
while (leftBoundary < rightBoundary) {
const temporaryStorage = nums[leftBoundary];
nums[leftBoundary] = nums[rightBoundary];
nums[rightBoundary] = temporaryStorage;
leftBoundary++;
rightBoundary--;
}
};
swapElements(0, arraySize - 1);
swapElements(0, rotationsCount - 1);
swapElements(rotationsCount, arraySize - 1);
};