232. Implement Queue using Stacks

Solution

We are going to use two stacks, pushStack and popStack.

For Queue.push() always pushStack.push()

For Queue.pop():

  • if popStack is empty move all elements from pushStack.
  • then popStack.pop().

For Queue.peek():

  • if popStack is empty move all elements from pushStack.
  • then popStack.peek().

For Queue.empty() just check the pushStack and popStack length.

Since I’m using JavaScript I use an Array, which doesn’t have peek(), so I just use stack[lenght-1].

var MyQueue = function() {
    this.pushStack = [];
    this.popStack = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.pushStack.push(x);
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    if (this.popStack.length === 0) {
        while(this.pushStack[this.pushStack.length - 1]) {
            const p = this.pushStack.pop();
            this.popStack.push(p);
        }
    }
    return this.popStack.pop();
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if (this.popStack.length === 0) {
        while(this.pushStack[this.pushStack.length - 1]) {
            const p = this.pushStack.pop();
            this.popStack.push(p);
        }
    }
    return this.popStack[this.popStack.length - 1];
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return (this.pushStack.length === 0 && this.popStack.length === 0);
};

/** 
 * Your MyQueue object will be instantiated and called as such:
 * var obj = new MyQueue()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.peek()
 * var param_4 = obj.empty()
 */

Complexity

  • Time Complexity: O(1), amortized, or O(N) over N operations, even if one of those operation will take longer.
  • Space Complexity: O(N), the number of elements, split between the two stacks.

All Solutions