Implement Queue using Stacks
Build a first-in-first-out (FIFO) queue using nothing but two stacks as the underlying storage. It needs to support push(x) (add an element to the back), pop() (remove the element at the front), peek() (look at the front element without removing it), and empty() (report whether the queue has anything left). The only moves allowed on the underlying stacks are the usual ones — pushing to the top, popping or peeking the top, checking the size, and checking if a stack is empty.
Calls to pop() and peek() occur only when the queue is non-empty.
Sample Input and Output
Example 1 · Run Sample
constructorArgs = []
operations = [["push",1],["push",2],["peek"],["pop"],["empty"],["pop"],["empty"]] [null,null,1,1,false,2,true] Example 2
constructorArgs = []
operations = [["empty"],["push",3],["pop"],["push",4],["peek"]] [true,null,3,null,4] - 1 <= x <= 9
- At most 100 calls to push, pop, peek, empty
Test Cases (2)
Approach: Two Stacks (Amortized)
Use an input stack for pushes and an output stack for pops. When the output stack is empty and a pop/peek is needed, transfer all elements from the input stack to the output stack, reversing the order. This gives amortized O(1) per operation.
function implementQueueUsingStacks() {
const inStack = [], outStack = [];
return {
push(x) { inStack.push(x); },
pop() {
if (!outStack.length) while (inStack.length) outStack.push(inStack.pop());
return outStack.pop();
},
peek() {
if (!outStack.length) while (inStack.length) outStack.push(inStack.pop());
return outStack[outStack.length - 1];
},
empty() { return !inStack.length && !outStack.length; }
};
}Time Complexity: Amortized O(1) per operation
Space Complexity: O(n)
Saved in this browser only. Private to you.