Challenge - 5 Problems
Array Rotation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Left Rotation by 2
What is the output of the following JavaScript code that rotates an array to the left by 2 positions?
DSA Javascript
const arr = [10, 20, 30, 40, 50]; const rotateLeft = (array, k) => { const n = array.length; k = k % n; return array.slice(k).concat(array.slice(0, k)); }; console.log(rotateLeft(arr, 2));
Attempts:
2 left
💡 Hint
Think about moving the first two elements to the end of the array.
✗ Incorrect
Left rotation by 2 means the first two elements (10, 20) move to the end, so the array becomes [30, 40, 50, 10, 20].
❓ Predict Output
intermediateOutput of Right Rotation by 3
What is the output of this JavaScript code that rotates an array to the right by 3 positions?
DSA Javascript
const arr = [1, 2, 3, 4, 5, 6]; const rotateRight = (array, k) => { const n = array.length; k = k % n; return array.slice(n - k).concat(array.slice(0, n - k)); }; console.log(rotateRight(arr, 3));
Attempts:
2 left
💡 Hint
Right rotation by 3 means last 3 elements come to the front.
✗ Incorrect
Right rotation by 3 moves last three elements (4,5,6) to the front, resulting in [4, 5, 6, 1, 2, 3].
🧠 Conceptual
advancedTime Complexity of Rotation Using Slicing
What is the time complexity of rotating an array of size n by k positions using the slicing and concatenation method shown in previous examples?
Attempts:
2 left
💡 Hint
Consider how many elements are copied during slicing and concatenation.
✗ Incorrect
Slicing and concatenation each copy parts of the array, so total operations scale linearly with n.
❓ Predict Output
advancedOutput of In-Place Left Rotation by 1
What is the output of this JavaScript code that rotates an array to the left by 1 position in-place?
DSA Javascript
const arr = [7, 8, 9, 10]; const rotateLeftInPlace = (array) => { const first = array.shift(); array.push(first); return array; }; console.log(rotateLeftInPlace(arr));
Attempts:
2 left
💡 Hint
The first element is removed and added to the end.
✗ Incorrect
shift() removes 7, push() adds it to the end, resulting in [8, 9, 10, 7].
❓ Predict Output
expertOutput After Multiple Rotations
Given the code below, what is the final state of the array after performing the rotations?
DSA Javascript
let arr = [1, 2, 3, 4, 5]; const rotateLeft = (array, k) => { const n = array.length; k = k % n; return array.slice(k).concat(array.slice(0, k)); }; arr = rotateLeft(arr, 2); arr = rotateLeft(arr, 3); console.log(arr);
Attempts:
2 left
💡 Hint
Think about the effect of rotating left by 2, then by 3 on the same array.
✗ Incorrect
Rotating left by 2 then by 3 is equivalent to rotating left by (2+3)=5, which is a full rotation returning the array to original.
