Implement Queue Using Stacks

Try to solve the Implement Queue Using Stacks problem.

Statement#

Design a custom queue, MyQueue, using only two stacks. Implement the Push(), Pop(), Peek(), and Empty() methods:

  • Void Push(int x): Pushes element at the end of the queue.
  • Int Pop(): Removes and returns the element from the front of the queue.
  • Int Peek(): Returns the element at the front of the queue.
  • Boolean Empty(): Returns TRUE if the queue is empty. Otherwise FALSE.

You are required to only use the standard stack operations, which means that only the Push() to top, Peek() and Pop() from the top, Size(), and Is Empty() operations are valid.

Note: In some interview questions, Void Push(int x) and Int Pop() might be referred to as Void Enqueue(int x) and Int Dequeue(), respectively.

Constraints:

  • 1<=1 <= x <=100<= 100
  • A maximum of 100100 calls can be made to Push(), Pop(), Peek(), and Empty().
  • The Pop() and Peek() methods will always be called on non-empty stacks.

Examples#

Created with Fabric.js 3.6.6 Sample Example 1 Input 1. push(1) 2. push(2) 3. peek() 4. pop() 5. empty() Output 1. null 2. null 3. 1 4. 1 5. false -------------------------------------

1 of 3

Created with Fabric.js 3.6.6 Input Output 1. pop() 2. push(2) 3. pop() 4. peek() 5. empty() 1. null 2. null 3. 2 4. null 5. true Sample Example 2 -------------------------------------

2 of 3

Created with Fabric.js 3.6.6 Input Output Sample Example 3 1. push(1) 2. pop() 3. push(2) 4. peek() 5. empty() 1. null 2. 1 3. null 4. 2 5. false -------------------------------------

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Implement Queue Using Stacks

1

What is the output for the following series of commands?

 push(10), push(20), pop(), peek()
A)

NULL, NULL, 20, 10

B)

NULL, NULL, 10, 20

C)

10, 20, NULL, NULL

D)

10, 20, 10, 20

Question 1 of 30 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks required to implement the Push() operation.

Drag and drop the cards to rearrange them in the correct sequence.

Transfer the existing elements from stack 1 to stack 2.

Push the new element in stack 1.

Transfer the elements back to stack 1.


Try it yourself#

Implement your solution in myqueue.py in the following coding playground. We have provided some useful code templates in the other file that you may build on to solve this problem.

Python
myqueue.py
stack.py
Input #1
Input #2
Implement Queue using Stacks

Solution: Largest Rectangle in Histogram

Solution: Implement Queue Using Stacks