Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to rotate the array to the right by one position.
DSA Javascript
function rotateRightByOne(arr) {
const last = arr.pop();
arr.[1](last);
return arr;
}
console.log(rotateRightByOne([1, 2, 3, 4]));Attempts:
3 left
💡 Hint
Common Mistakes
Using push() adds the element to the end, leaving the array unchanged.
Using shift() or pop() removes elements from the wrong end.
✗ Incorrect
We remove the last element with pop(), then add it to the front using unshift() to rotate right by one.
2fill in blank
mediumComplete the code to rotate the array to the left by one position.
DSA Javascript
function rotateLeftByOne(arr) {
const first = arr.[1]();
arr.push(first);
return arr;
}
console.log(rotateLeftByOne([1, 2, 3, 4]));Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() removes the last element, not the first.
Using unshift() adds elements to the start, not removes.
✗ Incorrect
shift() removes the first element, which we then add to the end with push() to rotate left by one.
3fill in blank
hardComplete the code to rotate the array to the right by k positions.
DSA Javascript
function rotateRight(arr, k) {
k = k % arr.length;
const rotated = arr.slice(-k).concat(arr.[1](0, arr.length - k));
return rotated;
}
console.log(rotateRight([1, 2, 3, 4, 5], 2));Attempts:
3 left
💡 Hint
Common Mistakes
Using splice() modifies the original array.
Using pop or shift removes only one element, not a range.
✗ Incorrect
slice(0, arr.length - k) extracts the first part of the array to concatenate after the last k elements.
4fill in blank
hardFill both blanks to create a function that rotates the array to the left by k positions using slice and concat.
DSA Javascript
function rotateLeft(arr, k) {
k = k % arr.length;
return arr.[1](k).[2](arr.slice(0, k));
}
console.log(rotateLeft([10, 20, 30, 40, 50], 3));Attempts:
3 left
💡 Hint
Common Mistakes
Using splice instead of slice changes the original array.
Using push instead of concat does not join arrays.
✗ Incorrect
slice(k) gets the array from k to end, concat joins the first k elements at the end.
5fill in blank
hardFill all three blanks to implement an in-place rotation of the array to the right by k positions using reverse.
DSA Javascript
function reverse(arr, start, end) {
while (start < end) {
[arr[start], arr[end]] = [arr[end], arr[start]];
start++;
end--;
}
}
function rotateRightInPlace(arr, k) {
k = k % arr.length;
reverse(arr, 0, arr.length - 1);
reverse(arr, 0, [1]);
reverse(arr, [2], [3]);
return arr;
}
console.log(rotateRightInPlace([1, 2, 3, 4, 5, 6, 7], 3));Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong indices causes incorrect rotation.
Not adjusting k with modulo can cause errors when k > arr.length.
✗ Incorrect
After reversing the whole array, reverse the first k elements (0 to k-1), then reverse the rest (k to end).
