Implement Queue Using Stacks
Problem Description
Implement a first-in-first-out (FIFO) queue using only two stacks.
Implement MyQueue() and:
- push(x): Push x to the back of the queue.
- pop(): Remove and return the element from the front.
- peek(): Return the element at the front without removing.
- empty(): Return true if the queue is empty.
DE Shaw Tier 2 — LC 232.
Optimal: Two stacks (inbox/outbox). Push always goes to inbox. Pop/peek: if outbox is empty, pour inbox into outbox (reversing order). Amortized O(1) per operation.
Talk-track: 'Each element is moved at most twice — once into inbox, once into outbox. Total work is O(n), amortized O(1).'
Example Test Cases
Example 1
Input: [["MyQueue","push","push","peek","pop","empty"],[[],[1],[2],[],[],[]]]
Expected: [null,null,null,1,1,false]
Example 2
Input: [["MyQueue","push","pop","push","peek","empty"],[[],[1],[],[2],[],[]]]
Expected: [null,null,1,null,2,false]
Run your code to see the results