Queue Using Two Stacks
Implement a queue using two stacks. Your implementation should support the following operations:
enqueue(value)- Add element to the queuedequeue()- Remove and return the front element from the queuepeek()- Return the front element without removing itisEmpty()- Check if the queue is empty
dequeue and peek have the conventional non-empty-queue precondition: they are called only when the queue is not empty. Use isEmpty to inspect empty state. enqueue, dequeue, and peek values are signed 32-bit integers.
The amortized two-stack implementation should run in amortized $O(1)$ time per operation. The eager transfer implementation is a genuine pedagogical baseline that preserves FIFO behavior but performs $O(n)$ work per dequeue/peek inspection; expose it honestly and do not treat it as the optimized implementation.
Examples
Input: [["Queue","enqueue","peek","dequeue","isEmpty","isEmpty","enqueue","enqueue"],[[],[-1],[],[],[],[],[3],[7]]]
Output: [null,null,-1,-1,true,true,null,null]
Input: [["Queue","enqueue","dequeue","isEmpty","enqueue","isEmpty"],[[],[19],[],[],[13],[]]]
Output: [null,null,19,true,null,false]
Hints
Use two stacks: one for input (push) and one for output (pop).
On dequeue/peek, if the output stack is empty, transfer all elements from the input stack.
The eager baseline restores transferred elements after every inspection; the amortized two-stack approach leaves transferred elements in the output stack and gives amortized O(1) per operation.
Queue Using Two Stacks
Implement a queue using two stacks. Your implementation should support the following operations: