Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to add an element to the stack using a queue.
DSA Java
public void push(int x) {
queue.[1](x);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using remove() or poll() which remove elements instead of adding.
Using add() which can throw exceptions if the queue is full.
✗ Incorrect
The offer() method adds an element to the queue. It is the correct way to enqueue an element.
2fill in blank
mediumComplete the code to remove the front element from the queue.
DSA Java
int front = queue.[1]();Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() which only returns but does not remove the element.
Using offer() or add() which add elements instead of removing.
✗ Incorrect
poll() removes and returns the head of the queue, which is needed to simulate stack pop.
3fill in blank
hardFix the error in the code to rotate the queue elements after pushing.
DSA Java
for (int i = 0; i < queue.size() - 1; i++) { queue.[1](queue.[2]()); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() which does not remove the element.
Using remove() which throws exception if queue is empty.
✗ Incorrect
poll() removes the front element, and offer() adds it back. Using poll() twice would remove two elements incorrectly.
4fill in blank
hardFill both blanks to correctly implement the pop method using the queue.
DSA Java
public int pop() {
return queue.[1]();
}
public int top() {
return queue.[2]();
}Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() in pop() which does not remove the element.
Using poll() in top() which removes the element.
✗ Incorrect
pop() removes and returns the front element using poll(), while top() returns the front element without removing it using peek().
5fill in blank
hardFill all three blanks to complete the push method that rotates the queue to simulate stack push.
DSA Java
public void push(int x) {
queue.[1](x);
int size = queue.[2]();
for (int i = 0; i < size - 1; i++) {
queue.[3](queue.poll());
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using add() instead of offer() which can throw exceptions.
Using incorrect method to get size or rotate the queue.
✗ Incorrect
offer() adds the element, size() gets the queue size, and offer() adds the polled element back to rotate the queue.
