Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to add an element to the top of the stack.
DSA Javascript
push(element) {
this.stack[this.top] = element;
this.top = this.top [1] 1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' to update the top index.
Forgetting to update the top index after push.
✗ Incorrect
We increase the top index by 1 after adding an element to point to the next empty position.
2fill in blank
mediumComplete the code to check if the stack is empty.
DSA Javascript
isEmpty() {
return this.top [1] 0;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' which returns true when stack is not empty.
Using '>' or '<' which do not correctly check emptiness.
✗ Incorrect
The stack is empty when top index is exactly 0.
3fill in blank
hardFix the error in the pop method to correctly remove and return the top element.
DSA Javascript
pop() {
if (this.isEmpty()) {
return null;
}
this.top = this.top [1] 1;
return this.stack[this.top];
}Attempts:
3 left
💡 Hint
Common Mistakes
Increasing top index instead of decreasing it.
Returning stack element before updating top index.
✗ Incorrect
We decrease the top index by 1 before returning the element to remove the top element.
4fill in blank
hardFill both blanks to resize the stack array when full.
DSA Javascript
resize() {
let newSize = this.stack.length [1] 2;
let newStack = new Array(newSize);
for (let i = 0; i [2] this.stack.length; i++) {
newStack[i] = this.stack[i];
}
this.stack = newStack;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '*' to increase size.
Using '>' or '>=' in loop condition causing no iteration.
✗ Incorrect
We double the size by multiplying length by 2 and copy elements while i is less than original length.
5fill in blank
hardFill all three blanks to implement the push method with automatic resizing.
DSA Javascript
push(element) {
if (this.top [1] this.stack.length) {
this.resize();
}
this.stack[this.top] = element;
this.top = this.top [2] 1;
return this.stack[[3]];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>=' for resize condition.
Returning element at wrong index.
Not increasing top after push.
✗ Incorrect
We check if top is greater or equal to length to resize, then add element and increase top, finally return the added element at current top index.
