Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the top element of the stack without removing it.
DSA Javascript
function peek(stack) {
return stack[1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() removes the top element instead of just peeking.
Using push() or shift() does not return the top element.
✗ Incorrect
Using slice(-1)[0] returns the last element of the array (top of the stack) without removing it.
2fill in blank
mediumComplete the code to check if the stack is empty before peeking.
DSA Javascript
function peek(stack) {
if (stack.length === [1]) {
return null;
}
return stack.slice(-1)[0];
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking length === 1 instead of 0 causes wrong empty check.
Using undefined or -1 as length check is incorrect.
✗ Incorrect
Checking if stack.length === 0 means the stack is empty, so peek should return null.
3fill in blank
hardFix the error in the peek function to correctly return the top element or null if empty.
DSA Javascript
function peek(stack) {
if (stack.length === 0) {
return [1];
}
return stack[stack.length - 1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning undefined instead of null for empty stack.
Accessing stack[stack.length] which is undefined.
✗ Incorrect
Return null when stack is empty. Also, stack[stack.length] is undefined, should use stack[stack.length - 1].
4fill in blank
hardFill both blanks to complete the peek function that safely returns the top element or null if empty.
DSA Javascript
function peek(stack) {
if (stack.length === [1]) {
return [2];
}
return stack[stack.length - 1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 instead of 0 for empty check.
Returning undefined instead of null.
✗ Incorrect
Check if length is 0 to detect empty stack and return null in that case.
5fill in blank
hardFill all three blanks to implement peek using a ternary operator.
DSA Javascript
const peek = stack => stack.length === [1] ? [2] : stack[stack.length [3] 1];
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '-' for index calculation.
Returning undefined instead of null for empty stack.
✗ Incorrect
If stack is empty (length 0), return null; else return last element at index length - 1.
