Complete the code to rotate the array to the right by one position.
function rotateRightByOne(arr: number[]): number[] {
const last = arr[arr.length [1] 1];
for (let i = arr.length - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = last;
return arr;
}We subtract 1 from the array length to get the last index.
Complete the code to rotate the array to the left by one position.
function rotateLeftByOne(arr: number[]): number[] {
const first = arr[0];
for (let i = 0; i < arr.length - 1; i++) {
arr[i] = arr[i [1] 1];
}
arr[arr.length - 1] = first;
return arr;
}We add 1 to move each element to the left.
Fix the error in the code to rotate the array right by k positions using reversal.
function reverse(arr: number[], start: number, end: number): void {
while (start < end) {
const temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
function rotateRightByK(arr: number[], k: number): number[] {
k = k [1] arr.length;
reverse(arr, 0, arr.length - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, arr.length - 1);
return arr;
}We use modulo to handle cases where k is larger than array length.
Fill both blanks to create a function that rotates the array left by k positions using slicing.
function rotateLeftByK(arr: number[], k: number): number[] {
k = k [1] arr.length;
return arr.slice(k).[2](arr.slice(0, k));
}Modulo ensures k is within bounds, and concat joins the two slices.
Fill all three blanks to implement a function that rotates the array right by k positions using unshift and pop.
function rotateRightByKUsingPop(arr: number[], k: number): number[] {
k = k [1] arr.length;
for (let i = 0; i < k; i++) {
const last = arr.[2]();
arr.[3](last);
}
return arr;
}Modulo keeps k valid, pop removes last element, unshift adds it to front.
