Implement Queue Using Stacks
Try to solve the Implement Queue Using Stacks problem.
We'll cover the following
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:
-
x - A maximum of calls can be made to Push(), Pop(), Peek(), and Empty().
- The Pop() and Peek() methods will always be called on non-empty stacks.
Examples#
1 of 3
2 of 3
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
What is the output for the following series of commands?
push(10), push(20), pop(), peek()
NULL, NULL, 20, 10
NULL, NULL, 10, 20
10, 20, NULL, NULL
10, 20, 10, 20
Figure it out!#
We have a game for you to play. Rearrange the logical building blocks required to implement the Push() operation.
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.
Solution: Largest Rectangle in Histogram
Solution: Implement Queue Using Stacks