Design a FIFO queue using only stack operations.
Problem
Implement a queue data structure using only stack operations. Your queue should support the standard FIFO behavior while relying on stacks internally.
Create a class that supports the following operations:
push(x): add an element to the back of the queuepop(): remove and return the element at the front of the queuepeek(): return the front element without removing itempty(): return whether the queue has no elements
You may use one or more stacks to build the queue, but you should not use any built-in queue implementation.
The key challenge is to preserve queue order while only having stack access, which naturally works in LIFO order.
Input Format
- Operations are performed on a queue object.
push(x)receives one integerx.pop(),peek(), andempty()take no extra arguments.
Output Format
push(x)updates the internal state and returns nothing.pop()returns the front element.peek()returns the current front element.empty()returnstrueif the queue contains no elements, otherwisefalse.
Constraints
- Implement the queue using stack operations only.
- Assume all operations are called in a valid order for the chosen API.
- Aim for efficient amortized performance across a sequence of operations.
Example 1
Input
["MyQueue","push","push","peek","pop","empty"] [[],[1],[2],[],[],[]]
Output
[null,null,null,1,1,false]
Explanation
After pushing 1 and 2, the front of the queue is 1. peek() returns 1 without removing it, pop() removes 1, and the queue is still not empty because 2 remains.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.