Challenge - 5 Problems
Array Insertion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output after inserting elements at the beginning?
Consider the following JavaScript code that inserts elements at the beginning of an array. What will be the final state of the array after all insertions?
DSA Javascript
let arr = [3, 4, 5]; arr.unshift(2); arr.unshift(1); console.log(arr);
Attempts:
2 left
💡 Hint
Remember that unshift adds elements to the start of the array in the order they are called.
✗ Incorrect
The unshift method adds elements to the beginning of the array. First, 2 is added before 3,4,5 making [2,3,4,5]. Then 1 is added before 2, making [1,2,3,4,5].
❓ Predict Output
intermediateWhat is the output after multiple unshift calls?
What will be printed after running this code?
DSA Javascript
const arr = []; arr.unshift(10); arr.unshift(20); arr.unshift(30); console.log(arr);
Attempts:
2 left
💡 Hint
Each unshift adds the new element at the start, pushing existing elements right.
✗ Incorrect
The first unshift adds 10: [10]. Then 20 is added at start: [20,10]. Then 30 at start: [30,20,10].
🔧 Debug
advancedWhy does this code not insert at the beginning correctly?
The code below is intended to insert 0 at the beginning of the array, but it does not work as expected. What is the error?
DSA Javascript
let arr = [1, 2, 3]; arr.push(0); console.log(arr);
Attempts:
2 left
💡 Hint
Check the difference between push and unshift methods.
✗ Incorrect
push adds elements to the end of the array. To add at the beginning, unshift should be used.
❓ Predict Output
advancedWhat is the output after inserting multiple elements at the beginning?
What will be the final array after these insertions?
DSA Javascript
let arr = [4, 5]; arr.unshift(2, 3); arr.unshift(0, 1); console.log(arr);
Attempts:
2 left
💡 Hint
unshift can add multiple elements at once, preserving their order at the start.
✗ Incorrect
First unshift adds 2 and 3 at start: [2,3,4,5]. Then unshift adds 0 and 1 at start: [0,1,2,3,4,5].
❓ Predict Output
expertWhat is the output after inserting elements at the beginning inside a loop?
What will be the final array after running this code?
DSA Javascript
let arr = []; for(let i = 1; i <= 3; i++) { arr.unshift(i); } console.log(arr);
Attempts:
2 left
💡 Hint
Each unshift adds the new number at the start, pushing previous elements right.
✗ Incorrect
Loop inserts 1: [1], then 2 at start: [2,1], then 3 at start: [3,2,1].
