Easy
Quiz
#232 Implement Queue using Stacks
APPROACH
Build a FIFO (first-in-first-out) queue backed by exactly two stacks. The queue must support four operations: push, pop, peek, and empty.
Implement the MyQueue class:
- void push(int x) Appends element x to the back of the queue.
- int pop() Removes and returns the front element.
- int peek() Returns the front element without removing it.
- boolean empty() Returns true if the queue is empty, false otherwise.
Constraints:
- Only standard stack operations are allowed: push to top, peek/pop from top, size, and empty check.
- If your language has no native stack, a list or deque used strictly as a stack is acceptable.
Example 1:
Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]
Example 2:
Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
1 of 4
1:00
What is the optimal approach for this problem?