Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push an element into the queue using stack1.
DSA C++
void enqueue(int x) {
stack1.[1](x);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() instead of push() will remove elements instead of adding.
Using top() only accesses the top element without adding.
Using empty() checks if stack is empty, not for adding.
✗ Incorrect
To add an element to the queue, we push it onto stack1 using the push() method.
2fill in blank
mediumComplete the code to transfer elements from stack1 to stack2 when stack2 is empty during dequeue.
DSA C++
if (stack2.empty()) { while (!stack1.[1]()) { stack2.push(stack1.top()); stack1.pop(); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using top() as a condition causes errors since it returns the top element.
Using pop() as a condition is invalid since it removes elements.
Using size() returns a number, which is truthy but less clear than empty().
✗ Incorrect
We check if stack1 is empty using empty() before transferring elements to stack2.
3fill in blank
hardFix the error in the dequeue function to correctly remove and return the front element.
DSA C++
int dequeue() {
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
}
int x = stack2.[1]();
stack2.pop();
return x;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() to get the element causes loss without retrieval.
Using empty() returns a boolean, not the element.
Using push() is for adding, not retrieving.
✗ Incorrect
To get the front element, we use top() to access it before popping it from stack2.
4fill in blank
hardFill both blanks to check if the queue is empty using both stacks.
DSA C++
bool isEmpty() {
return stack1.[1]() && stack2.[2]();
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() or top() causes errors or wrong checks.
Using size() returns a number, not a boolean.
✗ Incorrect
The queue is empty only if both stacks are empty, checked by empty() method.
5fill in blank
hardFill all three blanks to implement the peek function that returns the front element without removing it.
DSA C++
int peek() {
if (stack2.[1]()) {
while (!stack1.[2]()) {
stack2.push(stack1.top());
stack1.pop();
}
}
return stack2.[3]();
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() to get the element removes it, which is wrong for peek.
Using top() before transferring elements causes errors if stack2 is empty.
✗ Incorrect
We check if stack2 is empty, then transfer from stack1 if needed, and finally return the top element of stack2.
