I created a copy of the array to be able to track the rotation of the array by k numbers.
I first thought of this
function rotate(nums: number[], k: number): void {
let n = nums.length
let copy = [...nums];
for (let i = 0; i < n; i++) {
if (i + k >= n) {
nums[i + k - n] = copy[i]
}else{
nums[i + k] = copy[i]
}
};
};but then it led to repeating values for arrays with lengths of 1 and also i + k -n can still be greater than n after the subtraction. so instead i use the mod operator% to get the index to be rotated to
-
Time complexity:O(N)
-
Space complexity:O(N)
/**
Do not return anything, modify nums in-place instead.
*/
function rotate(nums: number[], k: number): void {
let n = nums.length
let copy = [...nums];
for (let i = 0; i < n; i++) {
nums[(i + k) % n] = copy[i]
};
};