Skip to problem
←

Implement Queue Using Stacks

Easy 0 attempts

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.

pop() returns the removed value. peek() returns the same front value without changing the queue. empty() returns a boolean; push() has no return value.

Function contract

Implement the factory function implementQueueUsingStacks. Fixtures contain constructor arguments and a list of [method, ...arguments] calls. Each fixture starts with a fresh instance.

Output: Return the specified result from each method. The displayed output lists results in call order; undefined results appear as null.

Example 1

Input
constructorArgs = []
operations = [["push",1],["push",2],["peek"],["pop"],["empty"],["pop"],["empty"]]
Output
[null,null,1,1,false,2,true]

Example 2

Input
constructorArgs = []
operations = [["empty"],["push",3],["pop"],["push",4],["peek"]]
Output
[true,null,3,null,4]
Constraints
  • 1 <= x <= 9
  • At most 100 calls to push, pop, peek, empty
  • pop and peek are called only when the queue is nonempty.
Topics

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.

javascript
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; a single pop or peek can take O(n) when it transfers the input stack. Each element transfers at most once.

Space Complexity: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript