Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to add an element to the queue using stack1.
DSA Javascript
enqueue(element) {
this.stack1.[1](element);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop' which removes an element instead of adding.
Using 'shift' or 'unshift' which are for queue operations, not stack.
✗ Incorrect
To add an element to the queue, we push it onto stack1.
2fill in blank
mediumComplete the code to check if the queue is empty.
DSA Javascript
isEmpty() {
return this.stack1.length === [1] && this.stack2.length === 0;
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking for length equal to 1 instead of 0.
Using null instead of zero for length comparison.
✗ Incorrect
The queue is empty if both stacks have zero length.
3fill in blank
hardFix the error in the dequeue method to correctly move elements from stack1 to stack2.
DSA Javascript
dequeue() {
if (this.stack2.length === 0) {
while (this.stack1.length > [1]) {
this.stack2.push(this.stack1.pop());
}
}
return this.stack2.pop();
}Attempts:
3 left
💡 Hint
Common Mistakes
Using length > 1 which skips the last element.
Using negative or null values in the condition.
✗ Incorrect
We move elements while stack1 is not empty, so length > 0.
4fill in blank
hardFill both blanks to complete the peek method that returns the front element without removing it.
DSA Javascript
peek() {
if (this.stack2.length === 0) {
while (this.stack1.length > [1]) {
this.stack2.[2](this.stack1.pop());
}
}
return this.stack2[this.stack2.length - 1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop' instead of 'push' when moving elements.
Using length > 1 which misses elements.
✗ Incorrect
We move elements while stack1 is not empty (length > 0) and push them onto stack2.
5fill in blank
hardFill all three blanks to complete the size method that returns the total number of elements in the queue.
DSA Javascript
size() {
return this.stack1.[1] + this.stack2.[2];
}
// Example usage:
const q = new Queue();
q.enqueue(1);
q.enqueue(2);
q.dequeue();
console.log(q.size()); // Should print [3]Attempts:
3 left
💡 Hint
Common Mistakes
Using 'size' which is not a JavaScript array property.
Incorrect expected output number.
✗ Incorrect
The size is the sum of lengths of both stacks. After enqueue 1, 2 and dequeue once, stack1 is empty (length 0) and stack2 has one element (length 1), total size is 1.
